简体   繁体   English

在componentDidMount中模拟axios调用时无法调用.then

[英]Can't call .then when mocking axios call inside componentDidMount

I'm trying to unit test componentDidMount while mocking an Axios call. 我在模拟Axios调用时尝试对componentDidMount进行单元测试。

// src/App.tsx
import axios_with_baseUrl from './axios-instance-with-baseUrl';
...

public componentDidMount() {
    axios_with_baseUrl.get('/data.json')
       .then(resp => this.setState({ stuff }));
}

// src/App.test.tsx
jest.mock('./axios-instance-with-baseUrl', () => {
    return {
       get: jest.fn(() => Promise.resolve(someFakeData))
    };
});

import axios_with_baseUrl from './axios-instance-with-baseUrl';

test('fetches data on componentDidMount', async () => {
    const app = enzyme.shallow(<App />);
    app.instance().componentDidMount()
       .then(() => {
           expect(axios_with_baseUrl.get).toHaveBeenCalled();
       });
});

When I test the above code, I get the following error message: 当我测试上面的代码时,我收到以下错误消息:

TypeError: Cannot read property 'then' of undefined

  26 | test('componentDidMount', async () => {
  27 |   const app = enzyme.shallow(<App />);
> 28 |   app.instance().componentDidMount()
     |   ^
  29 |     .then(() => {

I guess it makes sense since componentDidMount is a void method, but I'm not sure why tutorials like this do it this way. 我想这是有道理的,因为componentDidMount是一个无效的方法,但我不知道为什么像教程这样做这种方式。 Is it best to simply ignore that pattern? 最好只是忽略该模式吗?

This is another pattern that I found: 这是我发现的另一种模式:

await app.instance().componentDidMount();
expect(axios_with_baseUrl.get).toHaveBeenCalled();

The bigger question is: are either of the above good patterns for mocking Axios in unit tests? 更大的问题是:以上两种在单元测试中模拟Axios的良好模式中有哪些? Or should I just rely on something like axios-mock-adapter ? 还是我应该依靠axios-mock-adapter类的东西?

Just add return before axios_with_base_url to make promise 只需在axios_with_base_url之前添加return即可做出promise

public componentDidMount() {
    return axios_with_baseUrl.get('/data.json')
       .then(resp => this.setState({ stuff }));
}

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

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