Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock Axios as default export with Jest

How do I mock axios that export as default function?

I have the api helper that generalizes api request with axios()

api.js

export const callApi = (endpoint, method, data = {}) => {

  return axios({
    url: endpoint,
    method,
    data
  })
  .then((response) => // handle response)
  .catch((error) => // handle error)
};

api.spec.js

import axios from 'axios';
import { callApi } from './api';

describe('callApi()', () => {
  it('calls `axios()` with `endpoint`, `method` and `body`', () => {

    // mock axios()
    jest.spyOn(axios, 'default');

    const endpoint = '/endpoint';
    const method = 'post';
    const data = { foo: 'bar' };

    // call function
    callApi(endpoint, method, data);

    // assert axios()
    expect(axios.default).toBeCalledWith({ url: endpoint, method, data});
  });
}); 

result

Expected mock function to have been called with:
  [{"data": {"foo": "bar"}, "method": "post", "url": "/endpoint"}]
But it was not called.

The call works fine if I mock axios.get() or other methods, but not for just axios(). I don't want to change the definition of the callApi() function.

How do I mock default axios()? What did I miss?

like image 995
Sithideth Bouasavanh Avatar asked Sep 11 '18 11:09

Sithideth Bouasavanh


1 Answers

You cannot use jest.spyOn(axios, 'default') when you call axios directly (no default). Changing your implementation in api.js to be axios.default(...args) makes the test pass.


A potential change you can make is to use jest.mock('axios') instead of using jest.spyOn.

import axios from 'axios';
import { callApi } from './api';

jest.mock('axios');

// Make sure to resolve with a promise
axios.mockResolvedValue();

describe('callApi()', () => {
  it('calls `axios()` with `endpoint`, `method` and `body`', () => {
    const endpoint = '/endpoint';
    const method = 'post';
    const data = { foo: 'bar' };

    // call function
    callApi(endpoint, method, data);

    // assert axios()
    expect(axios).toBeCalledWith({ url: endpoint, method, data});
  });
}); 
like image 83
SimenB Avatar answered Oct 09 '22 00:10

SimenB