10

I'm trying to test my axios API functions in React.

Found this question here: how do i test axios in jest which pointed to using axios-mock-adapter

import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import chatbot from './chatbot';

describe('Chatbot', () => {
    it('returns data when sendMessage is called', done => {
        var mock = new MockAdapter(axios);
        const data = { response: true };
        mock.onGet('https://us-central1-hutoma-backend.cloudfunctions.net/chat').reply(200, data);

        chatbot.sendMessage(0, 'any').then(response => {
            expect(response).toEqual(data);
            done();
        });
    });
});

The real function:

/**
 * Retrieve all Akamai images
 * @param  {String} akamai Akamai url
 * @return {Thenable}      Resolved: Akamai images
 */
export const callGetAkamai = () =>
  makeRequest('/akamai', 'GET')
    .catch(defaultCatch('callGetAkamai'));

My test:

import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import { callGetAkamai } from './api';

describe('GetAkamai', () => {
  it('returns data when callGetAkamai is called', (done) => {
    console.log('MockAdapter', MockAdapter);
    const mock = new MockAdapter(axios);
    // const mock = axios.create({
    //   baseURL: 'https://us-central1-hutoma-backend.cloudfunctions.net/chat/'
    // });

    const data = { response: true };
    mock.onGet('https://us-central1-hutoma-backend.cloudfunctions.net/chat').reply(200, data);

    callGetAkamai().then((response) => {
      expect(response).toEqual(data);
      done();
    });
  });
});

enter image description here

Leon Gaban
  • 27,845
  • 80
  • 281
  • 473

2 Answers2

10

Are you mocking axios already? I have run into this issue myself, and after looking in all the wrong places, I realized I was already mocking axios with jest.

Put the following snippet in your setupTestFrameworkScriptFile:

const mockNoop = () => new Promise(() => {});

// Notice how `create` was not being mocked here...
jest.mock('axios', () => ({
  default: mockNoop,
  get: mockNoop,
  post: mockNoop,
  put: mockNoop,
  delete: mockNoop,
  patch: mockNoop
}));

While you might be able to do both, if you are using the axios-mock-adapter, you might want to remove your other mocks (and skip the snippet above).

User 1058612
  • 3,371
  • 24
  • 32
  • Do you do this in the test file itself or in like `__mocks__/axios.ts` that go like this: `export default { create: () => new Promise(() => {} ) }` – kyw Jul 17 '18 at 09:47
  • Good question, I updated the snippet above, but you would put in the `setupTestFrameworkScriptFile`. Hope that helps. – User 1058612 Jul 18 '18 at 13:22
  • Thanks. I fixed it myself. I answered it here https://stackoverflow.com/a/51414152/73323 – kyw Jul 19 '18 at 04:13
  • Also good to know: Even if the whole __mocks__/axios.ts is commented out, jest still mocks it! Deleting the file solved it for me. – p0wl Mar 31 '20 at 11:31
6

Adding this here since it's the first hit on google to the question and the answer selected doesn't really answer the question.

This problem typically happens when you are already mocking axios (very likely within a __mocks__ folder.

With jest, you can explicitly unmock, then call this axios-mock-adapter.

jest.unmock('axios');
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
...

axios-mock-adapter gives nice, flexible apis when working with external requests. However it doesn't globally prevent your app from making external calls that can be triggered by a test in a different component.

So I found both using axios-mock-adapter and doing a manual mock in the __mocks__ folder equally helpful.

Cent
  • 791
  • 6
  • 14
  • 1
    i used jest.unmock('axios'); and it solved the problem. So now my tests are running but the test is failing, so the moch is not working – asma May 18 '20 at 13:43
  • @asma after unmocking, did you do the import in the same file? You'd need to re-mock in the file you unmocked. Wondering if that was done? – Cent May 20 '20 at 08:34
  • yes i did the import and the mock, but its not working – asma May 21 '20 at 11:03
  • @asma same for me. Did you figure out the issue yet – Kuldeep Bhimte Jun 12 '20 at 08:12
  • @KuldeepBhimte not really, i postponed the issue. – asma Jun 12 '20 at 09:09
  • @Cent Could you please share a working code snippet? Facing the same issue. axios. create is not a functions error is gone but Mocking is not working. – LAXIT KUMAR Jan 31 '21 at 10:44