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

inject-query-lifecycle.test.ts

84 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'
9import type { Injector } from '@angular/core'
10​
11function setupLifecycle() {
12 const destroyCallbacks: Array<() => void> = []
13 const taskCleanups: Array<ReturnType<typeof vi.fn>> = []
14 const pendingTasks = {
15 add: vi.fn(() => {
16 const cleanup = vi.fn()
17 taskCleanups.push(cleanup)
18 return cleanup
19 }),
20 }
21 const destroyRef: {
22 destroyed: boolean
23 onDestroy: ReturnType<typeof vi.fn>
24 } = {
25 destroyed: false,
26 onDestroy: vi.fn((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 const injector = {
35 get(token: unknown) {
36 if (token === NgZone) return { run: (callback: () => void) => callback() }
37 if (token === PendingTasks) return pendingTasks
38 if (token === DestroyRef) return destroyRef
39 throw new Error(`Unexpected token: ${String(token)}`)
40 },
41 } as Injector
42​
43 return {
44 lifecycle: runInInjectionContext(injector, () =>
45 injectPendingTasksLifecycle(),
46 ),
47 pendingTasks,
48 taskCleanups,
49 destroy: () => {
50 destroyRef.destroyed = true
51 for (const callback of [...destroyCallbacks]) callback()
52 },
53 }
55​
56describe('QueryLifecycle', () => {
57 it('tracks pending state without registering duplicate tasks', () => {
58 const { lifecycle, pendingTasks, taskCleanups } = setupLifecycle()
59​
60 lifecycle.setPending(true)
61 lifecycle.setPending(true)
62​
63 expect(pendingTasks.add).toHaveBeenCalledOnce()
64​
65 lifecycle.setPending(false)
66 expect(taskCleanups[0]).toHaveBeenCalledOnce()
67​
68 lifecycle.setPending(true)
69 expect(pendingTasks.add).toHaveBeenCalledTimes(2)
70 })
71​
72 it('tracks destruction, releases its task, and cannot restart', () => {
73 const { lifecycle, pendingTasks, taskCleanups, destroy } = setupLifecycle()
74​
75 lifecycle.setPending(true)
76 destroy()
77​
78 expect(lifecycle.destroyed).toBe(true)
79 expect(taskCleanups[0]).toHaveBeenCalledOnce()
80​
81 lifecycle.setPending(true)
82 expect(pendingTasks.add).toHaveBeenCalledOnce()
83 })
84})