简体   繁体   中英

Can't call .then when mocking axios call inside 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(() => {

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();

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 ?

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 }));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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