【发布时间】:2016-06-03 03:17:18
【问题描述】:
我在 ES2015 中使用 Jest,试图测试这个在表单提交时进行 ajax 调用(使用 jQuery 完成的 ajax 调用)的组件。我只是想模拟返回的值并测试组件中的值是否更新。但我收到此错误:
- TypeError: Cannot read property 'then' of undefined
下面是ajax调用的代码:
accountValidate(name, email).then(this.showMsg);
showMsg(response) {
if (!response.authenticated) {
this.setState({msg: response.msg})
}
}
accountValidate(name, email) {
return($.ajax({
type: 'POST',
url: `/users/authenticate`,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
dataType: 'json',
data: JSON.stringify({name: name, email: email})
}));
}
这是 Jest 的代码:
let testMsg = {msg: 'testing msg'}
const msgResponse = Promise.resolve(testMsg);
accountValidate.mockClear();
accountValidate.mockReturnValue(msgResponse);
return msgResponse.then(() => {
console.log('test');
});
【问题讨论】:
-
这个错误意味着
accountValidate返回undefined或者errorResponse是undefined -
但组件工作正常。我能够进行 ajax 调用,接收响应数据并更新组件。只有测试失败。
-
accountValidate是否定义为代码中某处的函数?不清楚从哪里提取此代码 -this.setState()调用让我认为这是 React 组件的一部分? -
是的,它是定义的,你可以在上面看到。是的,它是带有 ES2015 的 React.js
-
@sayayin,
errorResponse是什么?
标签: javascript ajax reactjs jestjs