0

I have a utils class that uses axios to perform simple REST calls. When writing a jest unit test, although the tests pass, i seem to get an advisory error:

C:/home/dev/node_modules/axios/lib/core/createError.js:16
var error = new Error(message);

Error: Network Error
    at createErrorC:/home/dev/node_modules/axios/lib/core/createError.js:16
    config: {
        // ....
        header: { Accept: 'application/json, text/plain, */*' },
        withCredentials: true,
        responseType: 'json',
        method: 'get',
        url: 'http://mock.rest.server.com:1234/rest/user/data/adam',
        data: undefined
    },
    request: XMLHttpRequest {},
    response: undefined,
    isAxiosError: true,
    toJSON: [Function: toJSON]

utility.ts

import axios, { AxiosResponse } from 'axios'

axios.defaults.withCredentials = true;
axios.defaults.responseType = 'json';

export class UserUtils {

    public getUserConfig(userName: string): Promise<AxiosResponse> {
        if(!userName) {
            return;
        }

        return axios.get('http://mock.rest.server.com:1234/rest/user/data/' + userName);
    }

}

utility.test.ts

import axios from 'axios';
import { UserUtils } from '../../utility';

describe("Utility test", () => {
    const utils = new UserUtils();

    jest.mock('axios', () => {
        return {
          post: jest.fn(),
          get: jest.fn()
        }
    }

  // clear all mocks
    beforEach(() => {
        jest.clearAllMocks();
        jest.restoreAllMocks();
    });

    test("get user data",() => {
        jest.spyOn(axios, 'get');

        utils.getUserConfig('adam')
          .then(repsonse => {
            expect(axios.get).toHaveBeenCalledWith('http://mock.rest.server.com:1234/rest/user/data/adam');
        });
     });
});
Oam Psy
  • 8,555
  • 32
  • 93
  • 157

1 Answers1

1

Maybe this thread can help you: https://stackoverflow.com/a/51654713/20293448

Personally, I like using jest manual mocks (docs)

In my project, I have:

// src/__mocks__/axios.ts
import axios from 'axios';

const mockAxios = jest.genMockFromModule<typeof axios>('axios');

// this is the key to fix the axios.create() undefined error!
mockAxios.create = jest.fn(() => mockAxios);

// eslint-disable-next-line import/no-default-export
export default mockAxios;
// src/.../test.ts
import mockAxios from 'axios';

const mockedPost = mockAxios.post as jest.Mock;

beforeEach(() => {
  jest.clearAllMocks();
});

...

expect(mockedPost).toHaveBeenCalledWith(route, payload);

Hope this helps!