gpt4 book ai didi

javascript - 使用@testing-library/react 对 react-router 的链接进行最简单的测试

转载 作者:行者123 更新时间:2023-12-03 07:18:24 25 4
gpt4 key购买 nike

我试图了解如何通过@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
});

最佳答案

我就是这样做的: mock 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 - 使用@testing-library/react 对 react-router 的链接进行最简单的测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61869886/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com