小编典典

如何使用Jest监视类属性箭头功能

reactjs

如何使用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();
  });
});

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

有什么方法可以通过此测试而无需更改组件实现?


阅读 281

收藏
2020-07-22

共1个答案

小编典典

根据这一酶问题以及这一问题,您有两种选择:


选项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} />;
  }
}
2020-07-22