如何测试路由器对Jest的反应 [英] How can I testi React Router with Jest

查看:32
本文介绍了如何测试路由器对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"

这篇关于如何测试路由器对Jest的反应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆