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?
Aucun commentaire:
Enregistrer un commentaire