我有一个名为Component.ts
的假设性React组件,其代码结构类似于:
import React, { FC } from 'react';
import { useParams } from 'react-router-dom';
export const Guide: FC<{}> = () => {
const { serviceId } = useParams();
return (
<p>{serviceId}</p>
)
}
为了测试此组件的行为,我试图在我的Component.test.ts
文件中执行类似以下操作:
import React from 'react';
import { render } from '@testing-library/react';
import { Component } from './Component';
import { Route, MemoryRouter } from 'react-router-dom';
test('my Component test', async () => {
const someServiceId = 'some-service-id';
const { findByText } = render(
<MemoryRouter initialEntries={[`guides/${someServiceId}`]}>
<Route path='guides/:serviceId'>
<Guide />
</Route>
</MemoryRouter>
);
expect(await findByText(someServiceId)).toBeInTheDocument();
});
当我使用5.2.2
的{{1}}版本时,我的测试有效,但是由于我更新到react-router-dom
,所以测试失败了。 Jest在运行测试时显示以下消息:
6.0.0-beta.0
答案 0 :(得分:1)
经过大量搜索,我找到了答案in the test suite。
6.0.0-beta.0中的技巧是将<Route />
包裹在<Routes />
中。还要注意,组件是从react-router
而不是react-router-dom
导入的:
import {
MemoryRouter,
Routes,
Route,
} from 'react-router';
test('my Component test', async () => {
const someServiceId = 'some-service-id';
const { findByText } = render(
<MemoryRouter initialEntries={[`guides/${someServiceId}`]}>
<Routes>
<Route path='guides/:serviceId'>
<Guide />
</Route>
</Routes>
</MemoryRouter>
);
await waitFor(() => expect(findByText(someServiceId)).toBeInTheDocument());
});