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 { beforeEach, describe, expect, it } from 'vitest'
13import { TestBed } from '@angular/core/testing'
14import { signalProxy } from '../signal-proxy'
15β
16describe('signalProxy', () => {
17 const inputSignal = signal({
18 fn: () => 'bar',
19 baz: 'qux',
20 falsy: false,
21 zero: 0,
22 })
23 const proxy = signalProxy(inputSignal, ['fn'])
24β
25 it('should have computed fields', () => {
26 expect(proxy.baz()).toEqual('qux')
27 expect(isSignal(proxy.baz)).toBe(true)
28 })
29β
30 it('should pass through functions as-is', () => {
31 expect(proxy.fn()).toEqual('bar')
32 expect(isSignal(proxy.fn)).toBe(false)
33 })
34β
35 it('supports "in" operator', () => {
36 expect('baz' in proxy).toBe(true)
37 expect('falsy' in proxy).toBe(true)
38 expect('zero' in proxy).toBe(true)
39 expect('foo' in proxy).toBe(false)
40 })
41β
42 it('supports "Object.keys"', () => {
43 expect(Object.keys(proxy)).toEqual(['fn', 'baz', 'falsy', 'zero'])
44 })
45β
46 describe('in component fixture', () => {
47 @Component({
48 selector: 'app-test',
49 standalone: true,
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 it('should generate fixed fields after initial change detection run', async () => {
71 const number = signal(1)
72 const fixture = TestBed.createComponent(TestComponent, {
73 bindings: [inputBinding('number', number.asReadonly())],
74 })
75 fixture.detectChanges()
76 const instance = fixture.componentInstance
77β
78 expect(isSignal(instance.proxy.number)).toBe(true)
79 expect(instance.proxy.number()).toBe(1)
80 expect(instance.shortNumber).toBe(instance.proxy.number)
81β
82 expect(instance.proxy.fn()).toBe(2)
83 expect(isSignal(instance.proxy.fn)).toBe(false)
84 expect(instance.shortFn).toBe(instance.proxy.fn)
85 })
86β
87 it('should reflect updates on the proxy', async () => {
88 const number = signal(0)
89 const fixture = TestBed.createComponent(TestComponent, {
90 bindings: [inputBinding('number', number.asReadonly())],
91 })
92 fixture.detectChanges()
93 const instance = fixture.componentInstance
94β
95 expect(instance.shortNumber()).toBe(0)
96 expect(instance.shortFn()).toBe(1)
97β
98 number.set(1)
99 fixture.detectChanges()
100β
101 expect(instance.shortNumber()).toBe(1)
102 expect(instance.shortFn()).toBe(2)
103 })
104 })
105})