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

utils.tsx

78 lines2.2 KB

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