Uri Klar
Uri Klar

Reputation: 3988

Mock axios when using the axios constuctor function

I have an API utility function that calls axios using the constructor notation:

axios({
   method,
   url: `${BASE_URL}/${url}`,
   data
});

I want to mock this using Jest, but not quite sure how. I was only able to mock a specific axios function (get, post, etc.).

Does anyone have an example of mocking axios when using it this way?

Upvotes: 3

Views: 1665

Answers (1)

Lin Du
Lin Du

Reputation: 102207

You can use jest.mock(moduleName, factory, options) to mock axios function.

E.g.

index.js:

import axios from 'axios';

export function main() {
  const BASE_URL = 'https://stackoverflow.com';
  const url = 'api';
  const data = {};
  return axios({
    method: 'GET',
    url: `${BASE_URL}/${url}`,
    data,
  });
}

index.test.js:

import { main } from '.';
import axios from 'axios';

jest.mock('axios', () => jest.fn());

describe('59873406', () => {
  it('should pass', async () => {
    const mResponse = { data: 'mock data' };
    axios.mockResolvedValueOnce(mResponse);
    const response = await main();
    expect(response).toEqual(mResponse);
    expect(axios).toBeCalledWith({ method: 'GET', url: 'https://stackoverflow.com/api', data: {} });
  });
});

Unit test results with 100% coverage:

 PASS  src/stackoverflow/59873406/index.test.js
  59873406
    ✓ should pass (7ms)

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |      100 |      100 |      100 |      100 |                   |
 index.js |      100 |      100 |      100 |      100 |                   |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        5.362s, estimated 13s

Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59873406

Upvotes: 5

Related Questions