mirror of
https://github.com/langgenius/dify.git
synced 2026-02-24 18:05:11 +00:00
61 lines
1.8 KiB
TypeScript
61 lines
1.8 KiB
TypeScript
import type { UrlUpdateEvent } from 'nuqs/adapters/testing'
|
|
import type { ComponentProps, ReactElement, ReactNode } from 'react'
|
|
import type { Mock } from 'vitest'
|
|
import { render, renderHook } from '@testing-library/react'
|
|
import { NuqsTestingAdapter } from 'nuqs/adapters/testing'
|
|
import { vi } from 'vitest'
|
|
|
|
type NuqsSearchParams = ComponentProps<typeof NuqsTestingAdapter>['searchParams']
|
|
type NuqsOnUrlUpdate = (event: UrlUpdateEvent) => void
|
|
type NuqsOnUrlUpdateSpy = Mock<NuqsOnUrlUpdate>
|
|
|
|
type NuqsTestOptions = {
|
|
searchParams?: NuqsSearchParams
|
|
onUrlUpdate?: NuqsOnUrlUpdateSpy
|
|
}
|
|
|
|
type NuqsHookTestOptions<Props> = NuqsTestOptions & {
|
|
initialProps?: Props
|
|
}
|
|
|
|
type NuqsWrapperProps = {
|
|
children: ReactNode
|
|
}
|
|
|
|
export const createNuqsTestWrapper = (options: NuqsTestOptions = {}) => {
|
|
const { searchParams = '', onUrlUpdate } = options
|
|
const urlUpdateSpy = onUrlUpdate ?? vi.fn<NuqsOnUrlUpdate>()
|
|
const wrapper = ({ children }: NuqsWrapperProps) => (
|
|
<NuqsTestingAdapter searchParams={searchParams} onUrlUpdate={urlUpdateSpy}>
|
|
{children}
|
|
</NuqsTestingAdapter>
|
|
)
|
|
|
|
return {
|
|
wrapper,
|
|
onUrlUpdate: urlUpdateSpy,
|
|
}
|
|
}
|
|
|
|
export const renderWithNuqs = (ui: ReactElement, options: NuqsTestOptions = {}) => {
|
|
const { wrapper, onUrlUpdate } = createNuqsTestWrapper(options)
|
|
const rendered = render(ui, { wrapper })
|
|
return {
|
|
...rendered,
|
|
onUrlUpdate,
|
|
}
|
|
}
|
|
|
|
export const renderHookWithNuqs = <Result, Props = void>(
|
|
callback: (props: Props) => Result,
|
|
options: NuqsHookTestOptions<Props> = {},
|
|
) => {
|
|
const { initialProps, ...nuqsOptions } = options
|
|
const { wrapper, onUrlUpdate } = createNuqsTestWrapper(nuqsOptions)
|
|
const rendered = renderHook(callback, { wrapper, initialProps })
|
|
return {
|
|
...rendered,
|
|
onUrlUpdate,
|
|
}
|
|
}
|