Testing
Some tips on testing components that use `nuqs`
Since nuqs 2, you can unit-test components that use useQueryState(s)
hooks
by wrapping your rendered component in a NuqsTestingAdapter
, or using
the withNuqsTestingAdapter
higher-order component.
With Vitest
Here is an example for Vitest and Testing Library to test a button rendering a counter:
See issue #259 for more testing-related discussions.
With Jest
Since nuqs 2 is an ESM-only package, there are a few hoops you need to jump through to make it work with Jest. This is extracted from the Jest ESM guide.
- Add the following options to your jest.config.ts file:
- Change your test command to include the
--experimental-vm-modules
flag:
Adapt accordingly for Windows with cross-env
.
NuqsTestingAdapter
The withNuqsTestingAdapter
function is a higher-order component that
wraps your component with a NuqsTestingAdapter
, but you can also use
it directly.
It takes the following props:
searchParams
: The initial search params to use for the test. These can be a query string, aURLSearchParams
object or a record object with string values.
onUrlUpdate
, a function that will be called when the URL is updated by the component. It receives an object with:- the new search params as an instance of
URLSearchParams
- the new querystring (for convenience)
- the options used to update the URL.
- the new search params as an instance of
🧪 Internal/advanced options
-
rateLimitFactor
. By default, rate limiting is disabled when testing, as it can lead to unexpected behaviours. Setting this to 1 will enable rate limiting with the same factor as in production. -
resetUrlUpdateQueueOnMount
: clear the URL update queue before running the test. This istrue
by default to isolate tests, but you can set it tofalse
to keep the URL update queue between renders and match the production behaviour more closely.