JEST - TypeError:无法读取未定义的属性'then'

时间:2016-06-03 03:17:19

标签: javascript ajax reactjs jestjs

我正在使用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');
      });

1 个答案:

答案 0 :(得分:0)

真的很晚了,但也许对某人有帮助。 我会这样尝试:

let testMsg = {msg: 'testing msg'}

beforeEach(() => {
      (accountValidate: any).mockClear();
      (accountValidate: any).mockReturnValue(
        new Promise(resolve => {
          resolve(testMsg);
        })
      );
    });