"未定义的属性onClickHandler作为函数"错误?

时间:2018-04-13 11:18:00

标签: javascript reactjs unit-testing react-redux enzyme

enter image description here我正在尝试测试click函数是否被调用。但得到这个 错误 Attempted to wrap undefined property onClickHandler as function

这是我的代码 https://codesandbox.io/s/oq7kwzrnj5

it("check counter increment function is callled", () => {
    const sandbox = sinon.createSandbox();
    const spy = sandbox.spy(Counter.prototype, "onClickHandler");
    const wrapper = shallow(<Counter />);
    wrapper.find("button").simulate("click");
    expect(spy.called).toBe(true);
  });

1 个答案:

答案 0 :(得分:0)

这不起作用,因为onClickHandler不是class方法。你需要做一些调整。首先,将方法声明更改为:

onClickHandler() {
  const increamentCounter = this.state.counter + 1;
  this.setState({
    counter: increamentCounter
  });
};

然后在constructor中,您可以执行以下操作以保持组件正确绑定:

this.onClickHandler = this.onClickHandler.bind(this);

注意:绑定该类方法而不是使用构造函数的另一个选项是使用为您执行此操作的库。下面是一个可能的样子。

import React from "react";
import autoBindMethods from 'class-autobind-decorator';

class Counter extends React.Component {
  constructor() {
    super();
    this.state = {
      counter: 0
    };
  }

  onClickHandler() {
    const increamentCounter = this.state.counter + 1;
    this.setState({
      counter: increamentCounter
    });
  };

  render() {
    return (
      <div>
        <p>{this.state.counter}</p>
        <button onClick={this.onClickHandler}>INCREMENT</button>
      </div>
    );
  }
}

autoBindMethods(Counter);
export default Counter;