如何使用Jest

时间:2018-09-22 10:32:54

标签: reactjs jestjs enzyme spy

如何使用Jest监视类属性箭头功能?我有以下示例测试用例,失败了,错误为Expected mock function to have been called.

import React, {Component} from "react";
import {shallow} from "enzyme";

class App extends Component {
  onButtonClick = () => {
    // Button click logic.
  };

  render() {
    return <button onClick={this.onButtonClick} />;
  }
}

describe("when button is clicked", () => {
  it("should call onButtonClick", () => {
    const app = shallow(<App />);
    const onButtonClickSpy = jest.spyOn(app.instance(), "onButtonClick");

    const button = app.find("button");
    button.simulate("click");
    expect(onButtonClickSpy).toHaveBeenCalled();
  });
});

我可以通过将按钮的onClick属性更改为() => this.onButtonClick()来使测试通过,但宁愿不要仅出于测试目的而更改组件实现。

在不更改组件实现的情况下,有什么方法可以使该测试通过?

1 个答案:

答案 0 :(得分:11)

根据this enzyme issuethis one,您有两个选择:


选项1:在wrapper.update()之后致电spyOn

在您的情况下,应该是:

describe("when button is clicked", () => {
  it("should call onButtonClick", () => {
    const app = shallow(<App />);
    const onButtonClickSpy = jest.spyOn(app.instance(), "onButtonClick");

    # This should do the trick
    app.update();
    app.instance().forceUpdate();

    const button = app.find("button");
    button.simulate("click");
    expect(onButtonClickSpy).toHaveBeenCalled();
  });
});

选项2:不要使用类属性

因此,对于您来说,您必须将组件更改为:

class App extends Component {
  constructor(props) {
    super(props);

    this.onButtonClick = this.onButtonClick.bind(this);
 }

  onButtonClick() {
    // Button click logic.
  };

  render() {
    return <button onClick={this.onButtonClick} />;
  }
}