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

utils.tsx

81 lines2.3 KB

1import { MatcherFunction } from '@testing-library/dom/types/matches'
2import { render } from '@testing-library/react'
3import * as React from 'react'
4import { ReactQueryDevtools } from '..'
5​
6import {
7 QueryClient,
8 QueryClientProvider,
9 QueryCache,
10} from '@tanstack/react-query'
11​
12export function renderWithClient(
13 client: QueryClient,
14 ui: React.ReactElement,
15 devtoolsOptions: Parameters<typeof ReactQueryDevtools>[number] = {},
16): ReturnType<typeof render> {
17 const { rerender, ...result } = render(
18 <QueryClientProvider client={client} context={devtoolsOptions.context}>
19 <ReactQueryDevtools {...devtoolsOptions} />
20 {ui}
21 </QueryClientProvider>,
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 */
49export const getByTextContent =
50 (textToMatch: string): MatcherFunction =>
51 (_content, node) => {
52 if (!node) {
53 return false
54 }
55 const hasText = (currentNode: Element) =>
56 currentNode.textContent === textToMatch
57 const nodeHasText = hasText(node)
58 const childrenDontHaveText = Array.from(node.children).every(
59 (child) => !hasText(child as HTMLElement),
60 )
61​
62 return nodeHasText && childrenDontHaveText
63 }
64​
65interface CreateQueryClientResponse {
66 queryClient: QueryClient
67 queryCache: QueryCache
69​
70export const createQueryClient = (): CreateQueryClientResponse => {
71 const queryCache = new QueryCache()
72 const queryClient = new QueryClient({
73 queryCache,
74 defaultOptions: {
75 queries: {
76 staleTime: 0,
77 },
78 },
79 })
80 return { queryClient, queryCache }