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

testing.md

48 lines1.5 KB

1---
2id: testing
3title: Testing
4ref: docs/framework/react/guides/testing.md
5replace: { 'react-query': 'preact-query', 'React': 'Preact' }
6---
7​
8[//]: # 'Install'
9​
10Writing unit tests for these custom hooks can be done by means of the [Preact Testing Library](https://github.com/testing-library/preact-testing-library), which provides `renderHook` and re-exports the `@testing-library/dom` helpers such as `waitFor`.
11​
12Install this by running:
13​
14```sh
15npm install @testing-library/preact --save-dev
16```
17​
18[//]: # 'Install'
19[//]: # 'ExampleFirstTest'
20​
21```tsx
22import { renderHook, waitFor } from '@testing-library/preact'
23​
24const queryClient = new QueryClient()
25const wrapper = ({ children }) => (
26 <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
28​
29const { result } = renderHook(() => useCustomHook(), { wrapper })
30​
31await waitFor(() => expect(result.current.isSuccess).toBe(true))
32​
33expect(result.current.data).toEqual('Hello')
34```
35​
36[//]: # 'ExampleFirstTest'
37[//]: # 'NoteWaitFor1'
38​
39Here we are making use of `waitFor` and waiting until the query status indicates that the request has succeeded. This way we know that our hook has finished and should have the correct data.
40​
41[//]: # 'NoteWaitFor1'
42[//]: # 'NoteWaitFor2'
43[//]: # 'NoteWaitFor2'
44[//]: # 'FurtherReading'
45​
46For additional tips and an alternative setup using `mock-service-worker`, have a look at [TkDodo's article on testing](https://tkdodo.eu/blog/testing-react%2Dquery). It's written for a different framework adapter, but the same approach applies here.
47​
48[//]: # 'FurtherReading'