Dan*_*bbs 11 spy reactjs jestjs enzyme
如何使用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();
});
});
Run Code Online (Sandbox Code Playgroud)
我可以通过将按钮的onClickprop 更改为来使测试通过,() => this.onButtonClick()但宁愿不要仅出于测试目的而更改组件实现。
有什么方法可以通过此测试而无需更改组件实现?
Léo*_*din 16
选项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();
});
});
Run Code Online (Sandbox Code Playgroud)
选项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} />;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5308 次 |
| 最近记录: |