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

utils.tsx

74 lines2.0 KB

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