我想开玩笑地测试 history.push

丽太

我是测试的初学者。

我正在使用玩笑和酶编写测试。但是,当我尝试为 编写测试时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。

我不知道在哪里以及如何重写代码以使测试工作。你能告诉我怎么做吗?

幻灯片p2

你可以这样做:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章