в документации библиотеки тестирования React есть этот пример для написания модульных тестов для компонентов, использующих React Router. Более конкретно, в нем упоминается этот шаблонный фрагмент:
// test utils file
function renderWithRouter(
ui,
{
route = '/',
history = createMemoryHistory({ initialEntries: [route] }),
} = {}
) {
const Wrapper = ({ children }) => (
<Router history={history}>{children}</Router>
)
return {
...render(ui, { wrapper: Wrapper }),
// adding `history` to the returned utilities to allow us
// to reference it in our tests (just try to avoid using
// this to test implementation details).
history,
}
}
На основе сигнатуры типа функций createMemoryHistory
из пакета history
и render
из пакета @testing-library/react
, то есть:
export type RenderResult<Q extends Queries = typeof queries> = {...}
export function render(ui: React.ReactElement, options?: Omit<RenderOptions, 'queries'>): RenderResult;
export function render<Q extends Queries>(ui: React.ReactElement, options: RenderOptions<Q>): RenderResult<Q>;
Я попытался преобразовать приведенный выше фрагмент кода тестовой утилиты в код TypeScript. Я придумал следующее:
import { Queries, render, RenderOptions, RenderResult, queries } from "@testing-library/react"
import { createMemoryHistory, LocationState, MemoryHistory } from "history"
import React from "react"
import { Router } from "react-router-dom"
export type RouterOptions<S = LocationState> = {
route: string,
history?: MemoryHistory<S>
}
export type RenderWithRouterResult<Q extends Queries, S = LocationState> = RenderResult<Q> & {history: MemoryHistory<S>}
export function renderWithRouter<S>(ui: React.ReactElement, options?: Omit<RenderOptions, "queries">, routerOptions: RouterOptions<S> = {route: "/"}): RenderWithRouterResult<typeof queries,S>
export function renderWithRouter<Q extends Queries, S>(ui: React.ReactElement, options: RenderOptions<Q>, routerOptions: RouterOptions<S> = {route: "/"}): RenderWithRouterResult<Q,S> {
const routerHistory = routerOptions.history || createMemoryHistory({ initialEntries: [routerOptions.route] })
const routerElement: React.ComponentType = ({ children }) => (
<Router history={routerHistory}>{children}</Router>
)
return {
...render(ui, { wrapper: routerElement }),
// adding `history` to the returned utilities to allow us
// to reference it in our tests (just try to avoid using
// this to test implementation details).
history: routerHistory,
}
}
и некоторые сумасшедшие ошибки типов как для сигнатуры перегрузки, так и для возвращаемого типа, которые слишком длинные, чтобы vscode отображал их полностью.
Кто-нибудь может пожалуйста помогите мне исправить типы и перегрузки, указанные выше, пожалуйста?