Skip to content

Commit ee5ac41

Browse files
committed
test: Add referential equality tests
1 parent 1f5771e commit ee5ac41

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed
+80
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
import { act, renderHook } from '@testing-library/react'
2+
import type { ReactNode } from 'react'
3+
import React from 'react'
4+
import { describe, expect, it } from 'vitest'
5+
import { NuqsTestingAdapter } from './adapters/testing'
6+
import { parseAsArrayOf, parseAsJson, parseAsString } from './parsers'
7+
import { useQueryStates } from './useQueryStates'
8+
9+
function withSearchParams(
10+
searchParams?: string | URLSearchParams | Record<string, string>
11+
) {
12+
return (props: { children: ReactNode }) => (
13+
<NuqsTestingAdapter searchParams={searchParams} {...props} />
14+
)
15+
}
16+
17+
describe('useQueryStates', () => {
18+
const defaults = {
19+
str: 'foo',
20+
obj: { initial: 'state' },
21+
arr: [
22+
{
23+
initial: 'state'
24+
}
25+
]
26+
}
27+
28+
const hook = () => {
29+
return useQueryStates({
30+
str: parseAsString.withDefault(defaults.str),
31+
obj: parseAsJson<any>(x => x).withDefault(defaults.obj),
32+
arr: parseAsArrayOf(parseAsJson<any>(x => x)).withDefault(defaults.arr)
33+
})
34+
}
35+
36+
it('should have referential equality on default values', () => {
37+
const { result } = renderHook(hook, { wrapper: NuqsTestingAdapter })
38+
const [state] = result.current
39+
expect(state.str).toBe(defaults.str)
40+
expect(state.obj).toBe(defaults.obj)
41+
expect(state.arr).toBe(defaults.arr)
42+
expect(state.arr[0]).toBe(defaults.arr[0])
43+
})
44+
45+
it('should keep referential equality when resetting to defaults', () => {
46+
const { result } = renderHook(hook, {
47+
wrapper: withSearchParams({
48+
str: 'foo',
49+
obj: '{"hello":"world"}',
50+
arr: '{"obj":true},{"arr":true}'
51+
})
52+
})
53+
act(() => {
54+
result.current[1](null)
55+
})
56+
const [state] = result.current
57+
expect(state.str).toBe(defaults.str)
58+
expect(state.obj).toBe(defaults.obj)
59+
expect(state.arr).toBe(defaults.arr)
60+
expect(state.arr[0]).toBe(defaults.arr[0])
61+
})
62+
63+
it('should keep referential equality when unrelated keys change', () => {
64+
const { result } = renderHook(hook, {
65+
wrapper: withSearchParams({
66+
str: 'foo',
67+
obj: '{"hello":"world"}'
68+
// Keep arr as default
69+
})
70+
})
71+
const [{ obj: initialObj, arr: initialArr }] = result.current
72+
act(() => {
73+
result.current[1]({ str: 'bar' })
74+
})
75+
const [{ str, obj, arr }] = result.current
76+
expect(str).toBe('bar')
77+
expect(obj).toBe(initialObj)
78+
expect(arr).toBe(initialArr)
79+
})
80+
})

0 commit comments

Comments
 (0)