Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

inject-query-lifecycle.test.ts

83 lines2.3 KB

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(() => {
15 const cleanup = vi.fn()
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) => {
26 destroyCallbacks.push(callback)
27 return () => {
28 const index = destroyCallbacks.indexOf(callback)
29 if (index !== -1) destroyCallbacks.splice(index, 1)
30 }
31 }),
32 }
33 const injector = {
34 get(token: unknown) {
35 if (token === NgZone) return { run: (callback: () => void) => callback() }
36 if (token === PendingTasks) return pendingTasks
37 if (token === DestroyRef) return destroyRef
38 throw new Error(`Unexpected token: ${String(token)}`)
39 },
40 }
41​
42 return {
43 lifecycle: runInInjectionContext(injector, () =>
44 injectPendingTasksLifecycle(),
45 ),
46 pendingTasks,
47 taskCleanups,
48 destroy: () => {
49 destroyRef.destroyed = true
50 for (const callback of [...destroyCallbacks]) callback()
51 },
52 }
54​
55describe('QueryLifecycle', () => {
56 it('tracks pending state without registering duplicate tasks', () => {
57 const { lifecycle, pendingTasks, taskCleanups } = setupLifecycle()
58​
59 lifecycle.setPending(true)
60 lifecycle.setPending(true)
61​
62 expect(pendingTasks.add).toHaveBeenCalledOnce()
63​
64 lifecycle.setPending(false)
65 expect(taskCleanups[0]).toHaveBeenCalledOnce()
66​
67 lifecycle.setPending(true)
68 expect(pendingTasks.add).toHaveBeenCalledTimes(2)
69 })
70​
71 it('tracks destruction, releases its task, and cannot restart', () => {
72 const { lifecycle, pendingTasks, taskCleanups, destroy } = setupLifecycle()
73​
74 lifecycle.setPending(true)
75 destroy()
76​
77 expect(lifecycle.destroyed).toBe(true)
78 expect(taskCleanups[0]).toHaveBeenCalledOnce()
79​
80 lifecycle.setPending(true)
81 expect(pendingTasks.add).toHaveBeenCalledOnce()
82 })
83})