javascript - 使用@testing-library/react 对 react-router 的链接进行最简单的测试
问题描述
我试图了解如何通过@testing-library/react 最好地测试 react-router 的行为是否符合预期。
我能想到的最简单的测试是验证单击链接是否会更改 URL。我知道理想情况下我应该测试单击链接会呈现一个新组件,但这会给测试增加很多样板。
所以这是我失败的例子:
import { MemoryRouter } from 'react-router-dom';
import { render } from '@testing-library/react';
import { createMemoryHistory } from 'history';
it('routes to a new route', async () => {
const history = createMemoryHistory();
const { getByText } = render(
<MemoryRouter history={history}>
<Link to="/hello">Click me</Link>
</MemoryRouter>
);
fireEvent.click(getByText('Click me'));
await waitFor(() => expect(history.location.pathname).to.equal('/hello')); // Fails
});
解决方案
我就是这样做的:模拟 history.push,然后监视它的调用。
import { MemoryRouter } from 'react-router-dom';
import { render } from '@testing-library/react';
import { createMemoryHistory } from 'history';
it('routes to a new route', async () => {
const history = createMemoryHistory();
// mock push function
history.push = jest.fn();
const { getByText } = render(
<MemoryRouter history={history}>
<Link to="/hello">Click me</Link>
</MemoryRouter>
);
// could be userEvent.click
// https://testing-library.com/docs/ecosystem-user-event/#clickelement-eventinit-options
fireEvent.click(getByText('Click me'));
// spy on push calls, assert on url (parameter)
expect(history.push).toHaveBeenCalledWith('/hello');
});
推荐阅读
- javascript - 给定字符串如何用数组中的多个单词替换某些单词?
- sas - 努力尝试将此 txt 数据集读入 SAS
- macos - 未记录的 CoreAudio 控制类
- java - 从其他添加处理程序时,Netty channelActive 不起作用
- python - 返回熊猫数据框中“以”开头的所有字符串
- reactjs - 如何自动将新用户连接到 Firebase 实时数据库中的现有节点
- python - 无法让我的猜谜游戏将 Ask_Number 识别为整数
- java - Gradle 为 Ubuntu 上的现有文件抛出 NoSuchFileException
- c++ - 在 C++ 中读取 IBM 浮点数
- ios - Stretchy Layout 不适用于子视图控制器