Open History to see the last commit
1import {
2 DestroyRef,
3 NgZone,
4 PendingTasks,
5 runInInjectionContext,
6} from '@angular/core'
7import { describe, expect, it, vi } from 'vitest'
8import { injectPendingTasksLifecycle } from '../utils/inject-pending-tasks-lifecycle'
9β
10function setupLifecycle() {
11 const destroyCallbacks: Array<() => void> = []
12 const taskCleanups: Array<ReturnType<typeof vi.fn>> = []
13 const pendingTasks = {
14 add: vi.fn<() => () => void>(() => {
15 const cleanup = vi.fn<() => void>()
16 taskCleanups.push(cleanup)
17 return cleanup
18 }),
19 }
20 const destroyRef: {
21 destroyed: boolean
22 onDestroy: ReturnType<typeof vi.fn>
23 } = {
24 destroyed: false,
25 onDestroy: vi.fn<(callback: () => void) => () => void>(
26 (callback: () => void) => {
27 destroyCallbacks.push(callback)
28 return () => {
29 const index = destroyCallbacks.indexOf(callback)
30 if (index !== -1) destroyCallbacks.splice(index, 1)
31 }
32 },
33 ),
34 }
35 const injector = {
36 get(token: unknown) {
37 if (token === NgZone) return { run: (callback: () => void) => callback() }
38 if (token === PendingTasks) return pendingTasks
39 if (token === DestroyRef) return destroyRef
40 throw new Error(`Unexpected token: ${String(token)}`)
41 },
42 }
43β
44 return {
45 lifecycle: runInInjectionContext(injector, () =>
46 injectPendingTasksLifecycle(),
47 ),
48 pendingTasks,
49 taskCleanups,
50 destroy: () => {
51 destroyRef.destroyed = true
52 for (const callback of [...destroyCallbacks]) callback()
53 },
54 }
55}
56β
57describe('QueryLifecycle', () => {
58 it('tracks pending state without registering duplicate tasks', () => {
59 const { lifecycle, pendingTasks, taskCleanups } = setupLifecycle()
60β
61 lifecycle.setPending(true)
62 lifecycle.setPending(true)
63β
64 expect(pendingTasks.add).toHaveBeenCalledTimes(1)
65β
66 lifecycle.setPending(false)
67 expect(taskCleanups[0]).toHaveBeenCalledTimes(1)
68β
69 lifecycle.setPending(true)
70 expect(pendingTasks.add).toHaveBeenCalledTimes(2)
71 })
72β
73 it('tracks destruction, releases its task, and cannot restart', () => {
74 const { lifecycle, pendingTasks, taskCleanups, destroy } = setupLifecycle()
75β
76 lifecycle.setPending(true)
77 destroy()
78β
79 expect(lifecycle.destroyed).toBe(true)
80 expect(taskCleanups[0]).toHaveBeenCalledTimes(1)
81β
82 lifecycle.setPending(true)
83 expect(pendingTasks.add).toHaveBeenCalledTimes(1)
84 })
85})