forked from TanStack/query
/
utils.tsx
85 lines (76 loc) 路 2.35 KB
/
utils.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import { render, type RenderOptions } from '@testing-library/react'
import * as React from 'react'
import { ReactQueryDevtools } from '../devtools'
import {
QueryClient,
QueryClientProvider,
QueryCache,
} from '@tanstack/react-query'
export function renderWithClient(
client: QueryClient,
ui: React.ReactElement,
devtoolsOptions: Parameters<typeof ReactQueryDevtools>[number] = {},
renderOptions?: RenderOptions,
): ReturnType<typeof render> {
const { rerender, ...result } = render(
<QueryClientProvider client={client} context={devtoolsOptions.context}>
<ReactQueryDevtools {...devtoolsOptions} />
{ui}
</QueryClientProvider>,
renderOptions,
)
return {
...result,
rerender: (rerenderUi: React.ReactElement) =>
rerender(
<QueryClientProvider client={client} context={devtoolsOptions.context}>
<ReactQueryDevtools {...devtoolsOptions} />
{rerenderUi}
</QueryClientProvider>,
),
} as any
}
export function sleep(timeout: number): Promise<void> {
return new Promise((resolve) => {
setTimeout(resolve, timeout)
})
}
/**
* This method is useful for matching by text content when the text is splitted
* across different HTML elements which cannot be searched by normal
* *ByText methods. It returns a function that can be passed to the testing
* library's *ByText methods.
* @param textToMatch The string that needs to be matched
* @reference https://stackoverflow.com/a/56859650/8252081
*/
type MatcherFunction = (content: string, element: Element | null) => boolean
export const getByTextContent =
(textToMatch: string): MatcherFunction =>
(_content, node) => {
if (!node) {
return false
}
const hasText = (currentNode: Element) =>
currentNode.textContent === textToMatch
const nodeHasText = hasText(node)
const childrenDontHaveText = Array.from(node.children).every(
(child) => !hasText(child as HTMLElement),
)
return nodeHasText && childrenDontHaveText
}
interface CreateQueryClientResponse {
queryClient: QueryClient
queryCache: QueryCache
}
export const createQueryClient = (): CreateQueryClientResponse => {
const queryCache = new QueryCache()
const queryClient = new QueryClient({
queryCache,
defaultOptions: {
queries: {
staleTime: 0,
},
},
})
return { queryClient, queryCache }
}