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

utils.ts

78 lines1.9 KB

1import { vi } from 'vitest'
2import { act } from '@testing-library/react'
3import { QueryClient, onlineManager } from '..'
4import * as utils from '../utils'
5import type { SpyInstance } from 'vitest'
6import type { MutationOptions, QueryClientConfig } from '..'
7​
8export function createQueryClient(config?: QueryClientConfig): QueryClient {
9 return new QueryClient(config)
11​
12export function mockVisibilityState(
13 value: DocumentVisibilityState,
14): SpyInstance<[], DocumentVisibilityState> {
15 return vi.spyOn(document, 'visibilityState', 'get').mockReturnValue(value)
17​
18export function mockOnlineManagerIsOnline(
19 value: boolean,
20): SpyInstance<[], boolean> {
21 return vi.spyOn(onlineManager, 'isOnline').mockReturnValue(value)
23​
24let queryKeyCount = 0
25export function queryKey(): Array<string> {
26 queryKeyCount++
27 return [`query_${queryKeyCount}`]
29​
30export function sleep(timeout: number): Promise<void> {
31 return new Promise((resolve, _reject) => {
32 setTimeout(resolve, timeout)
33 })
35​
36export function setActTimeout(fn: () => void, ms?: number) {
37 return setTimeout(() => {
38 act(() => {
39 fn()
40 })
41 }, ms)
43​
44export const executeMutation = <TVariables>(
45 queryClient: QueryClient,
46 options: MutationOptions<any, any, TVariables, any>,
47 variables: TVariables,
48) => {
49 return queryClient
50 .getMutationCache()
51 .build(queryClient, options)
52 .execute(variables)
54​
55// This monkey-patches the isServer-value from utils,
56// so that we can pretend to be in a server environment
57export function setIsServer(isServer: boolean) {
58 const original = utils.isServer
59 Object.defineProperty(utils, 'isServer', {
60 get: () => isServer,
61 })
62​
63 return () => {
64 Object.defineProperty(utils, 'isServer', {
65 get: () => original,
66 })
67 }
69​
70export const doNotExecute = (_func: () => void) => true
71​
72export type Equal<X, Y> = (<T>() => T extends X ? 1 : 2) extends <
73 T,
74>() => T extends Y ? 1 : 2
75 ? true
76 : false
77​
78export type Expect<T extends true> = T