Jestjs 为什么不是';当我看到它是真的时,我的玩笑间谍就不会出现了吗?
我试图确定,当我看到间谍被正确地“注入”到我的组件中时,为什么我的Jest spy没有被调用?下面是我的一个非常简单的例子: TestComponent.jsJestjs 为什么不是';当我看到它是真的时,我的玩笑间谍就不会出现了吗?,jestjs,enzyme,Jestjs,Enzyme,我试图确定,当我看到间谍被正确地“注入”到我的组件中时,为什么我的Jest spy没有被调用?下面是我的一个非常简单的例子: TestComponent.js export default class TestComponent extends Component { constructor(props) { super(props); this.handleSubmit = this.handleSubmit.bind(this); } handleSubmit
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>
);
}
}
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();
});
});
导出默认类TestComponent扩展组件{
建造师(道具){
超级(道具);
this.handleSubmit=this.handleSubmit.bind(this);
}
handleSubmit(事件){
event&&event.preventDefault();
log(“handlesubmitcalled!”);
}
render(){
返回(
提交
);
}
}
TestComponent.test.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>
);
}
}
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();
});
});
description(“TestComponent测试”),()=>{
它(“'handleSubmit`在提交表单时被调用”,()=>{
常量包装器=浅();
const spy=jest.spyOn(wrapper.instance(),“handleSubmit”);
包装器。查找(“表单”)。模拟(“提交”);
期望(间谍)。已被调用();
});
});
如果我在wrapper.instance().handleSubmit
上执行console.log
,我可以清楚地看到spy已经被注入到对象的属性中,但是我的测试仍然失败,表明spy没有被调用
可在此处找到带有工作示例的CodeSandbox:
谢谢 最佳实践不是测试调用了
handleSubmit
,而是检查调用handleSubmit
的结果。话虽如此
问题
onSubmit
直接绑定到组件渲染时this.handleSubmit的值
解决方案 使用lambda函数(注意,)以便
onSubmit
在调用this.handleSubmit时调用其当前值:
<form onSubmit={() => this.handleSubmit()}>
this.handleSubmit()}>
我猜这是由于onSubmit函数以某种方式被异步调用的事实——我们将在这方面做更多的研究。