在componentDidMount中模拟axios调用时无法调用.then [英] Can't call .then when mocking axios call inside componentDidMount

查看:190
本文介绍了在componentDidMount中模拟axios调用时无法调用.then的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在模拟Axios调用时进行单元测试componentDidMount.

I'm trying to unit test componentDidMount while mocking an Axios call.

// 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(() => {

我想这很有意义,因为componentDidMount是一个无效方法,但是我不确定为什么

I guess it makes sense since componentDidMount is a void method, but I'm not sure why tutorials like this do it this way. 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();

更大的问题是:以上两种在单元测试中模拟Axios的良好模式中的一种吗?还是应该依靠axios-mock-adapter之类的东西?

The bigger question is: are either of the above good patterns for mocking Axios in unit tests? Or should I just rely on something like axios-mock-adapter?

推荐答案

只需在axios_with_base_url之前添加return即可生成promise

Just add return before axios_with_base_url to make promise

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

这篇关于在componentDidMount中模拟axios调用时无法调用.then的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆