如何使用Jest监视类属性箭头功能?我有以下示例测试用例,失败并显示以下错误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(); }); });
我可以通过将按钮的onClickprop 更改为来使测试通过,() => this.onButtonClick()但宁愿不要仅出于测试目的而更改组件实现。
onClick
() => this.onButtonClick()
有什么方法可以通过此测试而无需更改组件实现?
根据这一酶问题以及这一问题,您有两种选择:
选项1:呼叫wrapper.update()后spyOn
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} />; } }