gpt4 book ai didi

reactjs - React 测试库和 Jest 中的模拟路由器

转载 作者:行者123 更新时间:2023-12-05 01:06:37 25 4
gpt4 key购买 nike

我正在使用 React 测试库和 Jest 编写单元测试,并想检查我的 React 组件是否能够成功导航到下一页。

import { fireEvent, render, screen } from "@testing-library/react";
import React from 'react';
import { Provider } from 'react-redux';
import '@testing-library/jest-dom';
import appStore from '../../src/app/redux/store';
import { MemoryRouter, Route } from 'react-router-dom';
import { createMemoryHistory } from 'history';
import { Router } from 'react-router';

const setup = (initialEntries = []) => {
let inMemHistory = createMemoryHistory({ initialEntries });
const utils = render(
<Router history={inMemHistory}>
<Provider store={appStore}>
<Component-1 />

</Provider>
</Router>
);

const saveButtonElem = screen.getByRole('button', { name: "Save and Continue" });
return {
saveButtonElem,
inMemHistory,
...utils,
}
};

测试:

test('should be able to navigate', async () => {
const {
saveButtonElem,
inMemHistory,
getByText,
queryByText,
queryAllByText,
} = setup(["/component_add"]);

// Content of Test

// Saving Config
fireEvent.click(saveButtonElem);
console.info("Current Path", inMemHistory.location.pathname);
// Got /component_add on console
// Expected /component_data after clicking on save button

})

我尝试在点击保存按钮后等待 5 秒,然后尝试打印路径,但结果相同。

最佳答案

假设您使用 react-router,您可以使用 Memory router 进行更简单和高效的测试。在没有 IDE 支持的情况下键入时,我可能会出现拼写错误或语法错误。但它应该可以帮助您了解我的建议。

选项 1:

it("should route to the expected page", () => {
let mockHistory, mockLocation;
render(
<MemoryRouter initialEntries={["/currentUri"]}>
<Component1 />
// Dummy route that routes for all urls
<Route
path="*"
render={({ history, location }) => {
mockHistory= history;
mockLocation= location;
return null;
}}
/>
</MemoryRouter>
);
// navigate here on event
userEvent.click(screen.getByRole('button', {name: /Save/}));
expect(mockLocation.pathname).toBe("/expectedUri");
});

选项 2:

import { createMemoryHistory } from 'history';
import { Router } from 'react-router';

const renderWithHistory = (initialEntries= [], Component) => {
let inMemHistory = createMemoryHistory({
initialEntries
});
return {
...render(
<Router history={inMemHistory}>
<Component />
</Router >
), history };
};

it("should route to the expected page", () => {
const { history } = renderWithHistory(['/currentUri'], Component1);
// navigate here on event
userEvent.click(screen.getByRole('button', {name: /Save/}));
expect(history.location.pathname).toBe("/expectedUri");
});

关于reactjs - React 测试库和 Jest 中的模拟路由器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68692385/

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