如何测试路由器对Jest的反应

我是使用JEST进行测试的新手,我想测试以下代码。

import React from "react";
import "./ButtonLogin.css";
import { Link } from 'react-router-dom';

function ButtonLogin() {
    return (
        <Link to="/login"> <button className="button-login">Iniciar sesión</button></Link>
    )
}

export default ButtonLogin;
import { MemoryRouter } from 'react-router-dom';
import { render, fireEvent, Link } from '@testing-library/react';
import { ButtonLogin } from './ButtonLogin';

it('routes to a new route', async () => {

  ButtonLogin = jest.fn();

  const { getByText } = render(
    <MemoryRouter ButtonLogin={ButtonLogin}>
      <Link to="/login">Iniciar sesión</Link>
    </MemoryRouter>
  );

  fireEvent.click(getByText('Iniciar sesión'));

  expect(ButtonLogin).toHaveBeenCalledWith('/login');
});

我执行了以下测试,但测试失败,并且在第9行得到以下错误。 路由至新路由

"ButtonLogin" is read-only.

解决方案

可以使用createMemoryHistory函数和Router组件进行测试。创建一个带有初始条目的内存历史记录来模拟当前位置,这样我们就不依赖于真实的浏览器环境。激发Click事件后,断言pathname是否正确更改。

ButtonLogin.tsx

import React from 'react';
import { Link } from 'react-router-dom';

function ButtonLogin() {
  return (
    <Link to="/login">
      <button className="button-login">Iniciar sesión</button>
    </Link>
  );
}

export default ButtonLogin;

ButtonLogin.test.tsx

import { fireEvent, render } from '@testing-library/react';
import React from 'react';
import { Router } from 'react-router-dom';
import ButtonLogin from './ButtonLogin';
import { createMemoryHistory } from 'history';
describe('ButtonLogin', () => {
  test('should pass', () => {
    const history = createMemoryHistory({ initialEntries: ['/home'] });
    const { getByText } = render(
      <Router history={history}>
        <ButtonLogin />
      </Router>
    );
    expect(history.location.pathname).toBe('/home');
    fireEvent.click(getByText('Iniciar sesión'));
    expect(history.location.pathname).toBe('/login');
  });
});

测试结果:

 PASS  examples/69878146/ButtonLogin.test.tsx (10.675 s)
  ButtonLogin
    ✓ should pass (41 ms)

-----------------|---------|----------|---------|---------|-------------------
File             | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-----------------|---------|----------|---------|---------|-------------------
All files        |     100 |      100 |     100 |     100 |                   
 ButtonLogin.tsx |     100 |      100 |     100 |     100 |                   
-----------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        11.722 s, estimated 12 s

包版本:"react-router-dom": "^5.2.0"

相关文章