Skip to content

Commit

Permalink
test: Add dynamic keys test
Browse files Browse the repository at this point in the history
  • Loading branch information
franky47 committed Jan 14, 2025
1 parent c0467ed commit c5f62b1
Showing 1 changed file with 67 additions and 1 deletion.
68 changes: 67 additions & 1 deletion packages/nuqs/src/useQueryStates.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,12 @@ import {
withNuqsTestingAdapter,
type OnUrlUpdateFunction
} from './adapters/testing'
import { parseAsArrayOf, parseAsJson, parseAsString } from './parsers'
import {
parseAsArrayOf,
parseAsInteger,
parseAsJson,
parseAsString
} from './parsers'
import { useQueryStates } from './useQueryStates'

describe('useQueryStates: referential equality', () => {
Expand Down Expand Up @@ -233,3 +238,64 @@ describe('useQueryStates: clearOnDefault', () => {
expect(onUrlUpdate.mock.calls[0]![0].queryString).toEqual('')
})
})

describe('useQueryStates: dynamic keys', () => {
it('supports dynamic keys', () => {
const useTestHook = (keys: string[] = ['a', 'b']) =>
useQueryStates({
[keys[0]!]: parseAsInteger,
[keys[1]!]: parseAsInteger
})
const { result, rerender } = renderHook(useTestHook, {
wrapper: withNuqsTestingAdapter({
searchParams: '?a=1&b=2&c=3&d=4'
})
})
expect(result.current[0].a).toEqual(1)
expect(result.current[0].b).toEqual(2)
expect(result.current[0].c).toBeUndefined()
expect(result.current[0].d).toBeUndefined()
rerender(['c', 'd'])
expect(result.current[0].a).toBeUndefined()
expect(result.current[0].b).toBeUndefined()
expect(result.current[0].c).toEqual(3)
expect(result.current[0].d).toEqual(4)
})

it('supports dynamic keys with remapping', () => {
const useTestHook = (keys: string[] = ['a', 'b']) =>
useQueryStates(
{
[keys[0]!]: parseAsInteger,
[keys[1]!]: parseAsInteger
},
{
urlKeys: {
a: 'x',
b: 'y',
c: 'z'
}
}
)
const { result, rerender } = renderHook(useTestHook, {
wrapper: withNuqsTestingAdapter({
searchParams: '?x=1&y=2&z=3'
})
})
expect(result.current[0].a).toEqual(1)
expect(result.current[0].b).toEqual(2)
expect(result.current[0].c).toBeUndefined()
expect(result.current[0].d).toBeUndefined()
expect(result.current[0].x).toBeUndefined()
expect(result.current[0].y).toBeUndefined()
expect(result.current[0].z).toBeUndefined()
rerender(['c', 'd'])
expect(result.current[0].a).toBeUndefined()
expect(result.current[0].b).toBeUndefined()
expect(result.current[0].c).toEqual(3)
expect(result.current[0].d).toBeNull()
expect(result.current[0].x).toBeUndefined()
expect(result.current[0].y).toBeUndefined()
expect(result.current[0].z).toBeUndefined()
})
})

0 comments on commit c5f62b1

Please sign in to comment.