Open History to see the last commit
1import { describe, expect, test } from 'vitest'
2import {
3 ChangeDetectionStrategy,
4 Component,
5 computed,
6 effect,
7 input,
8 signal,
9} from '@angular/core'
10import { TestBed } from '@angular/core/testing'
11import { flushQueue, setFixtureSignalInputs } from '../../test-utils'
12import { lazyInit } from '../../../util/lazy-init/lazy-init'
13import type { WritableSignal } from '@angular/core'
14β
15describe('lazyInit', () => {
16 test('should init lazily in next tick when not accessing manually', async () => {
17 const mockFn = vi.fn()
18β
19 TestBed.runInInjectionContext(() => {
20 lazyInit(() => {
21 mockFn()
22 return {
23 data: signal(true),
24 }
25 })
26 })
27β
28 expect(mockFn).not.toHaveBeenCalled()
29β
30 await new Promise(setImmediate)
31β
32 expect(mockFn).toHaveBeenCalled()
33 })
34β
35 test('should init eagerly accessing manually', async () => {
36 const mockFn = vi.fn()
37β
38 TestBed.runInInjectionContext(() => {
39 const lazySignal = lazyInit(() => {
40 mockFn()
41 return {
42 data: signal(true),
43 }
44 })
45β
46 lazySignal.data()
47 })
48β
49 expect(mockFn).toHaveBeenCalled()
50 })
51β
52 test('should init lazily and only once', async () => {
53 const initCallFn = vi.fn()
54 const registerDataValue = vi.fn<(arg: number) => any>()
55β
56 let value!: { data: WritableSignal<number> }
57 const outerSignal = signal(0)
58β
59 TestBed.runInInjectionContext(() => {
60 value = lazyInit(() => {
61 initCallFn()
62β
63 void outerSignal()
64β
65 return { data: signal(0) }
66 })
67β
68 effect(() => registerDataValue(value.data()))
69 })
70β
71 value.data()
72β
73 await flushQueue()
74β
75 expect(outerSignal).toBeDefined()
76β
77 expect(initCallFn).toHaveBeenCalledTimes(1)
78β
79 outerSignal.set(1)
80 await flushQueue()
81 outerSignal.set(2)
82 await flushQueue()
83 value.data.set(4)
84 await flushQueue()
85β
86 expect(initCallFn).toHaveBeenCalledTimes(1)
87 expect(registerDataValue).toHaveBeenCalledTimes(2)
88 })
89β
90 test('should support required signal input', async () => {
91 @Component({
92 standalone: true,
93 template: `{{ call }} - {{ lazySignal.data() }}`,
94 changeDetection: ChangeDetectionStrategy.OnPush,
95 })
96 class Test {
97 readonly title = input.required<string>()
98 call = 0
99β
100 lazySignal = lazyInit(() => {
101 this.call++
102 return {
103 data: computed(() => this.title()),
104 }
105 })
106 }
107β
108 const fixture = TestBed.createComponent(Test)
109β
110 setFixtureSignalInputs(fixture, { title: 'newValue' })
111 expect(fixture.debugElement.nativeElement.textContent).toBe('0 - newValue')
112 await flushQueue()
113β
114 setFixtureSignalInputs(fixture, { title: 'updatedValue' })
115 expect(fixture.debugElement.nativeElement.textContent).toBe(
116 '1 - updatedValue',
117 )
118β
119 setFixtureSignalInputs(fixture, { title: 'newUpdatedValue' })
120 expect(fixture.debugElement.nativeElement.textContent).toBe(
121 '1 - newUpdatedValue',
122 )
123 })
124})