1.5 KiB
1.5 KiB
id, title, ref, replace
| id | title | ref | replace | ||||
|---|---|---|---|---|---|---|---|
| testing | Testing | docs/framework/react/guides/testing.md |
|
Writing unit tests for these custom hooks can be done by means of the Preact Testing Library, which provides renderHook and re-exports the @testing-library/dom helpers such as waitFor.
Install this by running:
npm install @testing-library/preact --save-dev
import { renderHook, waitFor } from '@testing-library/preact'
const queryClient = new QueryClient()
const wrapper = ({ children }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
)
const { result } = renderHook(() => useCustomHook(), { wrapper })
await waitFor(() => expect(result.current.isSuccess).toBe(true))
expect(result.current.data).toEqual('Hello')
Here 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.
For additional tips and an alternative setup using mock-service-worker, have a look at TkDodo's article on testing. It's written for a different framework adapter, but the same approach applies here.