简体   繁体   English

如何使用 Jest 监视类属性箭头函数

[英]How to spy on a class property arrow function using Jest

How can I spy on a class property arrow function using Jest?如何使用 Jest 监视类属性箭头函数? I have the following example test case which fails with the error Expected mock function to have been called.我有以下示例测试用例,它失败并显示错误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();
  });
});

I can make the test pass by changing the button's onClick prop to () => this.onButtonClick() but would prefer not to change my component implementation just for the sake of tests.我可以通过将按钮的onClick () => this.onButtonClick()更改为() => this.onButtonClick()来使测试通过,但不想仅仅为了测试而更改我的组件实现。

Is there any way to make this test pass without changing the component implementation?有什么方法可以在不更改组件实现的情况下使此测试通过?

According to this enzyme issue and this one , you have two options:根据这个酶问题这个问题,你有两个选择:


Option 1: Call wrapper.update() after spyOn选项 1:在spyOn之后调用wrapper.update()

In your case, that would be:在你的情况下,那将是:

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();
  });
});

Option 2: Don't use class property选项 2:不使用类属性

So, for you, you would have to change your component to:因此,对您而言,您必须将组件更改为:

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

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM