我想开玩笑地测试 history.push
I want to test history.push in jest
我是测试新手。
我正在使用 jest 和 enzyme 编写测试。
但是,当我尝试为 history.push()
编写测试时,出现以下错误。
TypeError: Cannot read property 'pathname' of undefined
.
这是我的测试代码和组件代码。
export default function Tags() {
const classes = useStyles();
const history = useHistory();
const isSelected = (category: string) => {
history.push(`/?category=${category}`);
};
return (
<>
<List className={classes.root} aria-label="contacts">
<ListItem button onClick={() => isSelected("backend")}>
<ListItemText primary="#backend" id="backend" />
</ListItem>
<ListItem button onClick={() => isSelected("frontend")}>
<ListItemText primary="#frontend" id="frontend" />
</ListItem>
</List>
</>
);
}
import * as React from "react";
import ReactDOM, * as ReactDom from "react-dom";
import Tags from "../Tags";
import { configure, mount, shallow } from "enzyme";
import Adapter from "enzyme-adapter-react-16";
import { fireEvent } from "@testing-library/react";
import { useHistory } from "react-router-dom";
configure({ adapter: new Adapter() });
jest.mock("react-router-dom", () => ({
useHistory: (): any => ({
push: jest.fn(),
}),
}));
describe("Tags", () => {
it("should be pushed correct path", () => {
const wrapper = mount(<Tags />);
const history: any = useHistory();
const backend = wrapper.find("div#backend").getDOMNode();
fireEvent.click(backend);
expect(history.location.pathname).toBe("?category=backend");
});
});
我想要实现的是,如果我点击按钮,它会访问正确的 url 或不。
我不知道在哪里以及如何重写代码以使测试工作。你能告诉我怎么做吗?
更新: 不再不推荐 模拟 useHistory
。相反,我们应该使用 <MemoryRouter initialEntries={['/']}/>
或 createMemoryHistory
,请参阅 https://testing-library.com/docs/example-react-router/
你可以这样做:
Tags.tsx
:
import { useHistory } from "react-router-dom";
import React from "react";
export default function Tags() {
const history = useHistory();
const isSelected = (category: string) => {
history.push(`/?category=${category}`);
};
return (
<>
<ul aria-label="contacts">
<li id="backend" onClick={() => isSelected("backend")}></li>
<li id="frontend" onClick={() => isSelected("frontend")}></li>
</ul>
</>
);
}
Tags.test.tsx
:
import React from "react";
import Tags from "./Tags";
import { mount } from "enzyme";
import ReactRouterDom from "react-router-dom";
const mHistory = {
push: jest.fn(),
};
jest.mock("react-router-dom", () => ({
...(jest.requireActual("react-router-dom") as typeof ReactRouterDom),
useHistory: jest.fn(() => mHistory),
}));
describe("Tags", () => {
afterAll(() => {
jest.resetAllMocks();
});
it("should be pushed correct path", () => {
const wrapper = mount(<Tags />);
const backend = wrapper.find("#backend");
backend.simulate("click");
expect(mHistory.push).toBeCalledWith("/?category=backend");
});
});
单元测试结果:
PASS examples/65245622/Tags.test.tsx
Tags
✓ should be pushed correct path (33 ms)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 88.89 | 100 | 75 | 88.89 |
Tags.tsx | 88.89 | 100 | 75 | 88.89 | 15
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 6.056 s
源代码:https://github.com/mrdulin/jest-v26-codelab/tree/main/examples/65245622
我是测试新手。
我正在使用 jest 和 enzyme 编写测试。
但是,当我尝试为 history.push()
编写测试时,出现以下错误。
TypeError: Cannot read property 'pathname' of undefined
.
这是我的测试代码和组件代码。
export default function Tags() {
const classes = useStyles();
const history = useHistory();
const isSelected = (category: string) => {
history.push(`/?category=${category}`);
};
return (
<>
<List className={classes.root} aria-label="contacts">
<ListItem button onClick={() => isSelected("backend")}>
<ListItemText primary="#backend" id="backend" />
</ListItem>
<ListItem button onClick={() => isSelected("frontend")}>
<ListItemText primary="#frontend" id="frontend" />
</ListItem>
</List>
</>
);
}
import * as React from "react";
import ReactDOM, * as ReactDom from "react-dom";
import Tags from "../Tags";
import { configure, mount, shallow } from "enzyme";
import Adapter from "enzyme-adapter-react-16";
import { fireEvent } from "@testing-library/react";
import { useHistory } from "react-router-dom";
configure({ adapter: new Adapter() });
jest.mock("react-router-dom", () => ({
useHistory: (): any => ({
push: jest.fn(),
}),
}));
describe("Tags", () => {
it("should be pushed correct path", () => {
const wrapper = mount(<Tags />);
const history: any = useHistory();
const backend = wrapper.find("div#backend").getDOMNode();
fireEvent.click(backend);
expect(history.location.pathname).toBe("?category=backend");
});
});
我想要实现的是,如果我点击按钮,它会访问正确的 url 或不。
我不知道在哪里以及如何重写代码以使测试工作。你能告诉我怎么做吗?
更新: 不再不推荐 模拟 useHistory
。相反,我们应该使用 <MemoryRouter initialEntries={['/']}/>
或 createMemoryHistory
,请参阅 https://testing-library.com/docs/example-react-router/
你可以这样做:
Tags.tsx
:
import { useHistory } from "react-router-dom";
import React from "react";
export default function Tags() {
const history = useHistory();
const isSelected = (category: string) => {
history.push(`/?category=${category}`);
};
return (
<>
<ul aria-label="contacts">
<li id="backend" onClick={() => isSelected("backend")}></li>
<li id="frontend" onClick={() => isSelected("frontend")}></li>
</ul>
</>
);
}
Tags.test.tsx
:
import React from "react";
import Tags from "./Tags";
import { mount } from "enzyme";
import ReactRouterDom from "react-router-dom";
const mHistory = {
push: jest.fn(),
};
jest.mock("react-router-dom", () => ({
...(jest.requireActual("react-router-dom") as typeof ReactRouterDom),
useHistory: jest.fn(() => mHistory),
}));
describe("Tags", () => {
afterAll(() => {
jest.resetAllMocks();
});
it("should be pushed correct path", () => {
const wrapper = mount(<Tags />);
const backend = wrapper.find("#backend");
backend.simulate("click");
expect(mHistory.push).toBeCalledWith("/?category=backend");
});
});
单元测试结果:
PASS examples/65245622/Tags.test.tsx
Tags
✓ should be pushed correct path (33 ms)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 88.89 | 100 | 75 | 88.89 |
Tags.tsx | 88.89 | 100 | 75 | 88.89 | 15
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 6.056 s
源代码:https://github.com/mrdulin/jest-v26-codelab/tree/main/examples/65245622