【发布时间】:2021-05-19 14:06:00
【问题描述】:
在我的代码中,我使用 react-router-dom 和 react-boostrap 元素。我一直在尝试做一些导航测试。我没有单元测试方面的经验,因此我将不胜感激。
我的路线在单独的文件中:
function Routes() {
return (
<div className="App">
<Header />
<Switch>
<Route exact path="/">
<Container>
<Row className="mt-3">
<Deck />
</Row>
<Row className="mt-3">
<Deck />
</Row>
</Container>
</Route>
<Route path="/about">
<h1>About_us</h1>
</Route>
<Route path="/dashboard">
<h1>Dashboard</h1>
</Route>
<Route path="/faq">
<h1>FAQ</h1>
</Route>
<Route path="/login">
<LoginPage />
</Route>
<Route path="/signup">
<SignUpPage />
</Route>
<Route>
<h1>Bad page</h1>
</Route>
</Switch>
</div>
);
}
export default Routes;
单元测试部分:
import '@testing-library/jest-dom';
import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import Routes from '../src/Routes.js';
test('full app navigating', async () => {
render(
<MemoryRouter initialEntries={['/']}>
<Routes />
</MemoryRouter>
);
expect(screen.getAllByText(/Card info/i)[0]).toBeInTheDocument();
fireEvent.click(screen.getByText(/Flashcards/i));
let result = await screen.findAllByText(/Card info/i);
expect(result[0]).toBeInTheDocument();
fireEvent.click(screen.getByText(/Home/i));
result = await screen.findAllByText(/Card info/i);
expect(result[0]).toBeInTheDocument();
fireEvent.click(screen.getByText(/About/i));
result = await screen.findByText(/About_us/i);
});
因此,在路径“/”上,我正在显示 Deck 组件,其中基本上包含“Card info”文本。这就是我搜索该文本的原因。另一方面,路径“/about”只呈现<h1>About_us</h1>。当我运行它时应用程序运行良好,但用玩笑进行测试会导致错误:
FAIL tests/Routes.test.js
× full app navigating (1123 ms)
● full app navigating
TestingLibraryElementError: Unable to find an element with the text: /About_us/i. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.
我的单元测试中似乎没有正确导航。
编辑:当我将 initialEntries 更改为“/about”时,应用程序会在该路由处呈现内容,因此路径自行工作。它必须与该行相关:
fireEvent.click(screen.getByText(/About/i));
About 只是一个带有 href="/about" 的
【问题讨论】:
标签: javascript reactjs unit-testing react-router react-bootstrap