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

inject-is-mutating.test.ts

80 lines2.1 KB

1import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2import { TestBed } from '@angular/core/testing'
3import {
4 Component,
5 Injector,
6 provideZonelessChangeDetection,
7} from '@angular/core'
8import { render } from '@testing-library/angular'
9import { queryKey, sleep } from '@tanstack/query-test-utils'
10import {
11 QueryClient,
12 injectIsMutating,
13 injectMutation,
14 provideTanStackQuery,
15} from '..'
16​
17describe('injectIsMutating', () => {
18 let queryClient: QueryClient
19​
20 beforeEach(() => {
21 vi.useFakeTimers()
22 queryClient = new QueryClient()
23​
24 TestBed.configureTestingModule({
25 providers: [
26 provideZonelessChangeDetection(),
27 provideTanStackQuery(queryClient),
28 ],
29 })
30 })
31​
32 afterEach(() => {
33 vi.useRealTimers()
34 })
35​
36 it('should properly return isMutating state', async () => {
37 const key = queryKey()
38​
39 @Component({
40 template: `<div>mutating: {{ isMutating() }}</div>`,
41 })
42 class Page {
43 readonly mutation = injectMutation(() => ({
44 mutationKey: key,
45 mutationFn: (params: { par1: string }) => sleep(10).then(() => params),
46 }))
47 readonly isMutating = injectIsMutating()
48 }
49​
50 const rendered = await render(Page)
51​
52 expect(rendered.getByText('mutating: 0')).toBeInTheDocument()
53​
54 rendered.fixture.componentInstance.mutation.mutate({ par1: 'par1' })
55​
56 await vi.advanceTimersByTimeAsync(0)
57 rendered.fixture.detectChanges()
58 expect(rendered.getByText('mutating: 1')).toBeInTheDocument()
59​
60 await vi.advanceTimersByTimeAsync(11)
61 rendered.fixture.detectChanges()
62 expect(rendered.getByText('mutating: 0')).toBeInTheDocument()
63 })
64​
65 describe('injection context', () => {
66 it('should throw NG0203 with descriptive error outside injection context', () => {
67 expect(() => {
68 injectIsMutating()
69 }).toThrow(/NG0203(.*?)injectIsMutating/)
70 })
71​
72 it('should be usable outside injection context when passing an injector', () => {
73 expect(
74 injectIsMutating(undefined, {
75 injector: TestBed.inject(Injector),
76 }),
77 ).not.toThrow()
78 })
79 })
80})