本文介绍了使用@testing-library/react 对 react-router 的链接进行最简单的测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试了解如何最好地测试 react-router 的行为是否符合 @testing-library/react 的预期.
I'm trying to understand how to best test that react-router behaves as expected with @testing-library/react.
我能想到的最简单的测试是验证单击链接是否会更改 URL.我知道理想情况下我应该测试点击链接会呈现一个新组件,但这会为测试增加很多样板.
The simplest test I can think of, is to verify that clicking a link changes the URL. I know that ideally I should test that clicking on a link renders a new component, but that adds a lot of boilerplate to the test.
这是我失败的例子:
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
});
推荐答案
我是这样做的:mocking history.push,然后监视它的调用.
This is how I do it : mocking history.push, then spy on its calls.
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');
});
这篇关于使用@testing-library/react 对 react-router 的链接进行最简单的测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!