Open History to see the last commit
1import { act } from '@testing-library/react'
2β
3import { QueryClient } from '@tanstack/query-core'
4import * as utils from '../utils'
5import type { MutationOptions, QueryClientConfig } from '@tanstack/query-core'
6β
7export const doNotExecute = (_func: () => void) => true
8β
9export function createQueryClient(config?: QueryClientConfig): QueryClient {
10 jest.spyOn(console, 'error').mockImplementation(() => undefined)
11 return new QueryClient({ logger: mockLogger, ...config })
12}
13β
14export function mockVisibilityState(value: DocumentVisibilityState) {
15 return jest.spyOn(document, 'visibilityState', 'get').mockReturnValue(value)
16}
17β
18export function mockNavigatorOnLine(value: boolean) {
19 return jest.spyOn(navigator, 'onLine', 'get').mockReturnValue(value)
20}
21β
22export const mockLogger = {
23 log: jest.fn(),
24 warn: jest.fn(),
25 error: jest.fn(),
26}
27β
28let queryKeyCount = 0
29export function queryKey(): Array<string> {
30 queryKeyCount++
31 return [`query_${queryKeyCount}`]
32}
33β
34export function sleep(timeout: number): Promise<void> {
35 return new Promise((resolve, _reject) => {
36 setTimeout(resolve, timeout)
37 })
38}
39β
40export function setActTimeout(fn: () => void, ms?: number) {
41 return setTimeout(() => {
42 act(() => {
43 fn()
44 })
45 }, ms)
46}
47β
48/**
49 * Assert the parameter is of a specific type.
50 */
51export const expectType = <T>(_: T): void => undefined
52β
53/**
54 * Assert the parameter is not typed as `any`
55 */
56export const expectTypeNotAny = <T>(_: 0 extends 1 & T ? never : T): void =>
57 undefined
58β
59export const executeMutation = (
60 queryClient: QueryClient,
61 options: MutationOptions<any, any, any, any>,
62): Promise<unknown> => {
63 return queryClient.getMutationCache().build(queryClient, options).execute()
64}
65β
66// This monkey-patches the isServer-value from utils,
67// so that we can pretend to be in a server environment
68export function setIsServer(isServer: boolean) {
69 const original = utils.isServer
70 Object.defineProperty(utils, 'isServer', {
71 get: () => isServer,
72 })
73β
74 return () => {
75 Object.defineProperty(utils, 'isServer', {
76 get: () => original,
77 })
78 }
79}