gpt4 book ai didi

javascript - 如何使用 Jest 测试 React Router

转载 作者:行者123 更新时间:2023-12-05 00:36:23 24 4
gpt4 key购买 nike

我刚开始使用 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 组件来测试它。创建一个带有初始条目的内存历史来模拟当前位置,这样我们就不会依赖真实的浏览器环境。触发点击事件后,断言 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"

关于javascript - 如何使用 Jest 测试 React Router,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69878146/

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