【问题标题】:JEST - TypeError: Cannot read property 'then' of undefinedJEST - TypeError:无法读取未定义的属性“then”
【发布时间】: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或者errorResponseundefined
  • 但组件工作正常。我能够进行 ajax 调用,接收响应数据并更新组件。只有测试失败。
  • accountValidate 是否定义为代码中某处的函数?不清楚从哪里提取此代码 - this.setState() 调用让我认为这是 React 组件的一部分?
  • 是的,它是定义的,你可以在上面看到。是的,它是带有 ES2015 的 React.js
  • @sayayin,errorResponse 是什么?

标签: javascript ajax reactjs jestjs


【解决方案1】:

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

let testMsg = {msg: 'testing msg'}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-19
    • 2014-09-07
    • 1970-01-01
    • 1970-01-01
    • 2014-11-26
    • 2014-11-29
    • 2016-09-20
    相关资源
    最近更新 更多