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

utils.tsx

84 lines2.4 KB

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