Skip to content

Commit

Permalink
test: Check referential equality when defaults change
Browse files Browse the repository at this point in the history
  • Loading branch information
franky47 committed Nov 14, 2024
1 parent ee5ac41 commit fbdf8d5
Showing 1 changed file with 37 additions and 19 deletions.
56 changes: 37 additions & 19 deletions packages/nuqs/src/useQueryStates.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,31 +10,36 @@ function withSearchParams(
searchParams?: string | URLSearchParams | Record<string, string>
) {
return (props: { children: ReactNode }) => (
<NuqsTestingAdapter searchParams={searchParams} {...props} />
<NuqsTestingAdapter
searchParams={searchParams}
{...props}
/>
)
}

describe('useQueryStates', () => {
const defaults = {
str: 'foo',
obj: { initial: 'state' },
arr: [
{
initial: 'state'
}
]
}
const defaults = {
str: 'foo',
obj: { initial: 'state' },
arr: [
{
initial: 'state'
}
]
}

const hook = () => {
return useQueryStates({
str: parseAsString.withDefault(defaults.str),
obj: parseAsJson<any>(x => x).withDefault(defaults.obj),
arr: parseAsArrayOf(parseAsJson<any>(x => x)).withDefault(defaults.arr)
})
}
const hook = ({ defaultValue } = { defaultValue: defaults.str }) => {
return useQueryStates({
str: parseAsString.withDefault(defaultValue),
obj: parseAsJson<any>(x => x).withDefault(defaults.obj),
arr: parseAsArrayOf(parseAsJson<any>(x => x)).withDefault(defaults.arr)
})
}

describe('useQueryStates', () => {
it('should have referential equality on default values', () => {
const { result } = renderHook(hook, { wrapper: NuqsTestingAdapter })
const { result } = renderHook(hook, {
wrapper: NuqsTestingAdapter
})
const [state] = result.current
expect(state.str).toBe(defaults.str)
expect(state.obj).toBe(defaults.obj)
Expand Down Expand Up @@ -77,4 +82,17 @@ describe('useQueryStates', () => {
expect(obj).toBe(initialObj)
expect(arr).toBe(initialArr)
})

it('should keep referential equality when default changes for another key', () => {
const { result, rerender } = renderHook(hook, {
wrapper: withSearchParams()
})
expect(result.current[0].str).toBe('foo')
rerender({ defaultValue: 'b' })
const [state] = result.current
expect(state.str).toBe('b')
expect(state.obj).toBe(defaults.obj)
expect(state.arr).toBe(defaults.arr)
expect(state.arr[0]).toBe(defaults.arr[0])
})
})

0 comments on commit fbdf8d5

Please sign in to comment.