generated from chiffre-io/template-library
-
-
Notifications
You must be signed in to change notification settings - Fork 162
/
Copy pathtesting.ts
76 lines (71 loc) · 1.92 KB
/
testing.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import { createElement, type ReactNode } from 'react'
import { resetQueue } from '../update-queue'
import { renderQueryString } from '../url-encoding'
import type { AdapterInterface, AdapterOptions } from './defs'
import { context } from './internal.context'
export type UrlUpdateEvent = {
searchParams: URLSearchParams
queryString: string
options: Required<AdapterOptions>
}
export type OnUrlUpdateFunction = (event: UrlUpdateEvent) => void
type TestingAdapterProps = {
searchParams?: string | Record<string, string> | URLSearchParams
onUrlUpdate?: OnUrlUpdateFunction
rateLimitFactor?: number
resetUrlUpdateQueueOnMount?: boolean
children: ReactNode
}
export function NuqsTestingAdapter({
resetUrlUpdateQueueOnMount = true,
...props
}: TestingAdapterProps) {
if (resetUrlUpdateQueueOnMount) {
resetQueue()
}
const useAdapter = (): AdapterInterface => ({
searchParams: new URLSearchParams(props.searchParams),
updateUrl(search, options) {
props.onUrlUpdate?.({
searchParams: search,
queryString: renderQueryString(search),
options
})
},
rateLimitFactor: props.rateLimitFactor ?? 0
})
return createElement(
context.Provider,
{ value: { useAdapter } },
props.children
)
}
/**
* A higher order component that wraps the children with the NuqsTestingAdapter
*
* It allows creating wrappers for testing purposes by providing only the
* necessary props to the NuqsTestingAdapter.
*
* Usage:
* ```tsx
* render(<MyComponent />, {
* wrapper: withNuqsTestingAdapter({ searchParams: '?foo=bar' })
* })
* ```
*/
export function withNuqsTestingAdapter(
props: Omit<TestingAdapterProps, 'children'> = {}
) {
return function NuqsTestingAdapterWrapper({
children
}: {
children: ReactNode
}) {
return createElement(
NuqsTestingAdapter,
// @ts-expect-error - Ignore missing children error
props,
children
)
}
}