首页 > 解决方案 > 使用@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
});

标签: javascriptreactjsreact-routerreact-testing-library

解决方案


我就是这样做的:模拟 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');
});

推荐阅读