我正在使用Jest和ES2015,试图在表单提交上测试这个组件进行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');
});
答案 0 :(得分:0)
真的很晚了,但也许对某人有帮助。 我会这样尝试:
let testMsg = {msg: 'testing msg'}
beforeEach(() => {
(accountValidate: any).mockClear();
(accountValidate: any).mockReturnValue(
new Promise(resolve => {
resolve(testMsg);
})
);
});