@@ -3,11 +3,41 @@ title: Testing
3
3
description : Some tips on testing components that use `nuqs`
4
4
---
5
5
6
- Currently, the best way to test the behaviour of your components using
7
- ` useQueryState(s) ` is end-to-end testing, with tools like Playwright or Cypress .
6
+ Since nuqs 2, you can unit- test components that use ` useQueryState(s){:ts} ` hooks
7
+ by wrapping your rendered component in a ` NuqsTestingAdapter{:ts} ` .
8
8
9
- Running components that use the Next.js router in isolation requires mocking it,
10
- which is being [ worked on] ( https://github.com/scottrippey/next-router-mock/pull/103 )
11
- for the app router.
9
+ Here is an example for Vitest and Testing Library to test a button rendering
10
+ a counter:
11
+
12
+ ``` tsx title="counter-button.test.tsx"
13
+ // [!code word:NuqsTestingAdapter]
14
+ import { render , screen } from ' @testing-library/react'
15
+ import userEvent from ' @testing-library/user-event'
16
+ import { NuqsTestingAdapter , type UrlUpdateEvent } from ' nuqs/adapters/testing'
17
+ import { describe , expect , it , vi } from ' vitest'
18
+ import { CounterButton } from ' ./counter-button'
19
+
20
+ it (' should increment the count when clicked' , async () => {
21
+ const user = userEvent .setup ()
22
+ const onUrlUpdate = vi .fn <[UrlUpdateEvent ]>()
23
+ render (<CounterButton />, {
24
+ // 1. Setup the test by passing initial search params / querystring:
25
+ wrapper : ({ children }) => (
26
+ <NuqsTestingAdapter searchParams = " ?count=42" onUrlUpdate = { onUrlUpdate } >
27
+ { children }
28
+ </NuqsTestingAdapter >
29
+ )
30
+ })
31
+ // 2. Act
32
+ const button = screen .getByRole (' button' )
33
+ await user .click (button )
34
+ // 3. Assert changes in the state and in the (mocked) URL
35
+ expect (button ).toHaveTextContent (' count is 43' )
36
+ expect (onUrlUpdate ).toHaveBeenCalledOnce ()
37
+ expect (onUrlUpdate .mock .calls [0 ][0 ].queryString ).toBe (' ?count=43' )
38
+ expect (onUrlUpdate .mock .calls [0 ][0 ].searchParams .get (' count' )).toBe (' 43' )
39
+ expect (onUrlUpdate .mock .calls [0 ][0 ].options .history ).toBe (' push' )
40
+ })
41
+ ```
12
42
13
43
See issue [ #259 ] ( https://github.com/47ng/nuqs/issues/259 ) for more testing-related discussions.
0 commit comments