Open History to see the last commit
1import {
2 ChangeDetectionStrategy,
3 Component,
4 computed,
5 input,
6 inputBinding,
7 isSignal,
8 provideZonelessChangeDetection,
9 signal,
10 untracked,
11} from '@angular/core'
12import { render } from '@testing-library/angular'
13import { beforeEach, describe, expect, test } from 'vitest'
14import { TestBed } from '@angular/core/testing'
15import { signalProxy } from '../signal-proxy'
16β
17describe('signalProxy', () => {
18 const inputSignal = signal({
19 fn: () => 'bar',
20 baz: 'qux',
21 falsy: false,
22 zero: 0,
23 })
24 const proxy = signalProxy(inputSignal, ['fn'])
25β
26 test('should have computed fields', () => {
27 expect(proxy.baz()).toEqual('qux')
28 expect(isSignal(proxy.baz)).toBe(true)
29 })
30β
31 test('should pass through functions as-is', () => {
32 expect(proxy.fn()).toEqual('bar')
33 expect(isSignal(proxy.fn)).toBe(false)
34 })
35β
36 test('supports "in" operator', () => {
37 expect('baz' in proxy).toBe(true)
38 expect('falsy' in proxy).toBe(true)
39 expect('zero' in proxy).toBe(true)
40 expect('foo' in proxy).toBe(false)
41 })
42β
43 test('supports "Object.keys"', () => {
44 expect(Object.keys(proxy)).toEqual(['fn', 'baz', 'falsy', 'zero'])
45 })
46β
47 describe('in component fixture', () => {
48 @Component({
49 selector: 'app-test',
50 template: '{{ proxy.baz() }}',
51 changeDetection: ChangeDetectionStrategy.OnPush,
52 })
53 class TestComponent {
54 number = input.required<number>()
55 obj = computed(() => ({
56 number: this.number(),
57 fn: () => untracked(this.number) + 1,
58 }))
59 proxy = signalProxy(this.obj, ['fn'])
60 shortNumber = this.proxy.number
61 shortFn = this.proxy.fn
62 }
63β
64 beforeEach(() => {
65 TestBed.configureTestingModule({
66 providers: [provideZonelessChangeDetection()],
67 })
68 })
69β
70 test('should generate fixed fields after initial change detection run', async () => {
71 const number = signal(1)
72 const rendered = await render(TestComponent, {
73 bindings: [inputBinding('number', number.asReadonly())],
74 })
75 const instance = rendered.fixture.componentInstance
76β
77 expect(isSignal(instance.proxy.number)).toBe(true)
78 expect(instance.proxy.number()).toBe(1)
79 expect(instance.shortNumber).toBe(instance.proxy.number)
80β
81 expect(instance.proxy.fn()).toBe(2)
82 expect(isSignal(instance.proxy.fn)).toBe(false)
83 expect(instance.shortFn).toBe(instance.proxy.fn)
84 })
85β
86 test('should reflect updates on the proxy', async () => {
87 const number = signal(0)
88 const rendered = await render(TestComponent, {
89 bindings: [inputBinding('number', number.asReadonly())],
90 })
91 const instance = rendered.fixture.componentInstance
92β
93 expect(instance.shortNumber()).toBe(0)
94 expect(instance.shortFn()).toBe(1)
95β
96 number.set(1)
97 rendered.fixture.detectChanges()
98β
99 expect(instance.shortNumber()).toBe(1)
100 expect(instance.shortFn()).toBe(2)
101 })
102 })
103})