如何使用 Jest 监视类属性箭头函数 [英] How to spy on a class property arrow function using Jest

查看:21
本文介绍了如何使用 Jest 监视类属性箭头函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 Jest 监视类属性箭头函数?我有以下示例测试用例,它失败并显示错误 Expected mock function to have been called.:

How can I spy on a class property arrow function using Jest? I have the following example test case which fails with the error 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() 但不想仅仅为了测试而改变我的组件实现.

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.

有没有什么办法可以在不改变组件实现的情况下让这个测试通过?

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:

选项 1:在 spyOn

在你的情况下,那将是:

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

<小时>

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

这篇关于如何使用 Jest 监视类属性箭头函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆