当我看到 spy 已正确“注入(inject)”到我的组件中时,我试图确定为什么我的 Jest spy 没有被调用?这是我的一个非常简单的例子:
TestComponent.js
export default class TestComponent extends Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event) {
event && event.preventDefault();
console.log("handleSubmit called!");
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<button className="submit-button" type="submit">
Submit
</button>
</form>
);
}
}
TestComponent.test.js
describe("TestComponent tests", () => {
it("`handleSubmit` is called when form is submitted", () => {
const wrapper = shallow(<TestComponent />);
const spy = jest.spyOn(wrapper.instance(), "handleSubmit");
wrapper.find("form").simulate("submit");
expect(spy).toHaveBeenCalled();
});
});
如果我在 wrapper.instance().handleSubmit
上执行 console.log
我可以清楚地看到 spy 已被注入(inject)到对象的属性中,但我的测试仍然失败,表明 spy 没有被调用。
可以在此处找到带有工作示例的 CodeSandbox:https://codesandbox.io/s/3ymkp3w5x1
谢谢!
最佳答案
最佳实践不是测试 handleSubmit
是否被调用,而只是检查调用 handleSubmit
的结果。话虽如此...
问题
onSubmit
在组件渲染时直接绑定(bind)到 this.handleSubmit
的值。
解决方案
使用 lambda 函数(注意 this might cause performance issues ),以便 onSubmit
在调用时调用 this.handleSubmit
的当前值:
<form onSubmit={() => this.handleSubmit()}>
关于jestjs - 为什么我的 Jest spy 没有显示为已调用,而我可以看到它已被调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53400938/