简体   繁体   English

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

[英]JEST - TypeError: Cannot read property 'then' of undefined

I am using Jest with ES2015, trying to test this component that makes an ajax call (ajax call done with jQuery) on form submit.我在 ES2015 中使用 Jest,试图测试这个组件,该组件在表单提交时进行 ajax 调用(使用 jQuery 完成的 ajax 调用)。 I'm just trying to mock the value returned and test the value is updated in the component.我只是想模拟返回的值并测试组件中的值是否更新。 But I receive this error:但我收到此错误:

  - TypeError: Cannot read property 'then' of undefined

Below is the code for ajax call:以下是 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})
    }));
  }

Here is the code for Jest:这是 Jest 的代码:

let testMsg = {msg: 'testing msg'}
const msgResponse = Promise.resolve(testMsg);
accountValidate.mockClear();
accountValidate.mockReturnValue(msgResponse);

      return msgResponse.then(() => {
          console.log('test');
      });

It's really late but maybe it helps someone.真的很晚了,但也许它可以帮助某人。 I would try it like that:我会这样尝试:

let testMsg = {msg: 'testing msg'}

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

Hi we were getting the same error in the test env we are using the typescript, testing-library/react嗨,我们在使用 typescript、testing-library/react 的测试环境中遇到了同样的错误

I was using node v 14.X but other person was using node 16.X and above they were getting this error.我使用的是 node v 14.X,但其他人使用的是 node 16.X 及更高版本,他们收到了这个错误。 So I updated my node version then able to replicate it on my local.所以我更新了我的节点版本,然后能够在我的本地复制它。

Then In test file, added the mockcall in the act, as it is affecting in updating the state also然后在测试文件中,在行为中添加了模拟调用,因为它也会影响更新 state

act(() => {
  mockAxios.post.mockImplementation(
    async () => Promise.resolve(availabilitySuccessMockData)
  );
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM