Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moxios - TypeError: Cannot read property 'adapter' of undefined

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

like image 474
Leon Gaban Avatar asked Dec 14 '25 10:12

Leon Gaban


2 Answers

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.

like image 139
flyrightsister Avatar answered Dec 16 '25 17:12

flyrightsister


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.
like image 28
Wang Dingwei Avatar answered Dec 16 '25 16:12

Wang Dingwei



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!