如何使用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()
来使测试通过,但宁愿不要仅出于测试目的而更改我的组件实现。有什么方法可以通过此测试而无需更改组件实现?
最佳答案
根据this enzyme issue和this 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} />;
}
}
关于reactjs - 如何使用Jest监视类属性箭头功能,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52455806/