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