Javascript JEST-TypeError:无法读取属性';然后';未定义的
我正在ES2015中使用Jest,试图测试这个组件,该组件在表单提交时进行ajax调用(使用jQuery完成ajax调用)。我只是试图模拟返回的值,并测试该值是否在组件中更新。但我收到了这个错误:Javascript JEST-TypeError:无法读取属性';然后';未定义的,javascript,ajax,reactjs,jestjs,Javascript,Ajax,Reactjs,Jestjs,我正在ES2015中使用Jest,试图测试这个组件,该组件在表单提交时进行ajax调用(使用jQuery完成ajax调用)。我只是试图模拟返回的值,并测试该值是否在组件中更新。但我收到了这个错误: - TypeError: Cannot read property 'then' of undefined 下面是ajax调用的代码: accountValidate(name, email).then(this.showMsg); showMsg(response) { if (!r
- 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');
});
真的很晚了,但也许这对某人有帮助。 我想这样做:
let testMsg = {msg: 'testing msg'}
beforeEach(() => {
(accountValidate: any).mockClear();
(accountValidate: any).mockReturnValue(
new Promise(resolve => {
resolve(testMsg);
})
);
});
该错误表示
accountValidate
返回undefined
或errorResponse
为undefined
,但组件工作正常。我能够进行ajax调用,接收响应数据并更新组件。只有测试失败。accountValidate
是否定义为代码中的某个函数?有点不清楚这个代码是从哪里提取的-调用this.setState()
使我认为这是React组件的一部分?是的,它是定义的,您可以在上面看到。是的,它是React.jsES2015@sayayin,什么是错误响应
?