3

Trying to test axios calls and trying the moxios package.

"axios": "^0.16.2", "moxios": "^0.4.0",

Found here: https://github.com/axios/moxios

Following there example, but my test errors out on the moxios.install() line:

import axios from 'axios'
import moxios from 'moxios'
import sinon from 'sinon'
import { equal } from 'assert'

describe('mocking axios requests', function () {

  describe('across entire suite', function () {

    beforeEach(function () {
      // import and pass your custom axios instance to this method
      moxios.install()
    })

My actual test

import axios from 'axios';
import moxios from 'moxios';
import sinon from 'sinon';
import { equal } from 'assert';

const akamaiData = {
  name: 'akamai'
};

describe('mocking axios requests', () => {
  describe('across entire suite', () => {
    beforeEach(() => {
      // import and pass your custom axios instance to this method
      moxios.install();
    });

    afterEach(() => {
      // import and pass your custom axios instance to this method
      moxios.uninstall();
    });

    it('should stub requests', (done) => {
      moxios.stubRequest('/akamai', {
        status: 200,
        response: {
          name: 'akamai'
        }
      });

      // const onFulfilled = sinon.spy();
      // axios.get('/akamai').then(onFulfilled);
      //
      // moxios.wait(() => {
      //   equal(onFulfilled.getCall(0).args[0], akamaiData);
      //   done();
      // });
    });
  });
});

enter image description here

I did find this closed issue here, however the fix "passing axios into the moxios.install(axios) function did not work"

https://github.com/axios/moxios/issues/15

Leon Gaban
  • 36,509
  • 115
  • 332
  • 529

3 Answers3

9

I was having the same problem. It turned out I had an axios.js file in my __mocks__ folder (leftover from a different attempt at mocking axios). That mock file took over the actual axios code -- but moxios needs the real axios code to function properly. When I removed the axios.js file from the __mocks__ folder, moxios worked as advertised.

1

For me it was about ES module interop. Try one of the two workarounds:

  • Try change import moxios from 'moxios' to import * as moxios from 'moxios'.
  • Set esModuleInterop to true in tsconfig.json.
Wang Dingwei
  • 4,661
  • 6
  • 32
  • 43
-3

Turns out I did not need moxios, in my test I did not want to make an actual API call... just needed to make sure that function was called. Fixed it with a test function.

import { makeRequest } from 'utils/services';
import { getImages } from './akamai';

global.console = { error: jest.fn() };

jest.mock('utils/services', () => ({
  makeRequest: jest.fn(() => Promise.resolve({ data: { foo: 'bar' } }))
}));

describe('Akamai getImages', () => {
  it('should make a request when we get images', () => {
    getImages();
    expect(makeRequest).toHaveBeenCalledWith('/akamai', 'GET');
  });
});
Leon Gaban
  • 36,509
  • 115
  • 332
  • 529