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