Reputation: 53
I am a beginner in testing.
I am writing a test using jest and enzyme.
However, when I tried to write a test for history.push()
, I got the following error.
TypeError: Cannot read property 'pathname' of undefined
.
Here is my test code and the component code.
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");
});
});
What I want to achieve is if I click on the button, it will access the correct url or not.
I don't know where and how to rewrite the code to make the test work. Can you please tell me how to do this?
Upvotes: 1
Views: 8148
Reputation: 102672
Update: Mocking useHistory
is not recommended anymore. Instead, we should use <MemoryRouter initialEntries={['/']}/>
or createMemoryHistory
, see https://testing-library.com/docs/example-react-router/
You can do this:
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");
});
});
unit test result:
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
source code: https://github.com/mrdulin/jest-v26-codelab/tree/main/examples/65245622
Upvotes: 3