ctimmerm / axios-mock-adapter

Axios adapter that allows to easily mock requests
MIT License
3.47k stars 245 forks source link

cannot read property defaults of undefined #289

Closed th3fallen closed 3 years ago

th3fallen commented 4 years ago

with the following..

import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';

const mockAdapter = new MockAdapter(axios);

global.axios = mockAdapter;

I'm getting the cannot read property defaults of undefined, I've tried all alternative import methods and still get the same result. Am I missing something?

qkreltms commented 4 years ago

Why don't you try axios.create() or axios() rather than axios because it needs AxiosInstance.

import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';

const mockAdapter = new MockAdapter(axios.create());

global.axios = mockAdapter;
jose920405 commented 3 years ago

Still happening

TypeError: Cannot read property 'defaults' of undefined

      at Object.<anonymous> (node_modules/axios-mock-adapter/src/utils.js:9:39)
      at Object.<anonymous> (node_modules/axios-mock-adapter/src/handle_request.js:3:13)

Into the utils.js file the line problem is

// < 0.13.0 will not have default headers set on a custom instance
var rejectWithError = !!axios.create().defaults.headers;

My axios version is "axios": "0.21.1".

mlshv commented 3 years ago

@jose920405 seems like you are trying to set global.axios to mockAdapter which is wrong. MockAdapter instance is not an axios instance

Refer to example in readme:

var axios = require("axios");
var MockAdapter = require("axios-mock-adapter");

var mock = new MockAdapter(axios);

mock.onGet("/users").reply(200, {
  users: [{ id: 1, name: "John Smith" }],
});

axios.get("/users").then(function (response) {
  console.log(response.data);
});

You need to do something like

import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';

const a = axios.create()
const mockAdapter = new MockAdapter(a);

global.axios = a;
ctimmerm commented 3 years ago

@mlshv thanks for your comment!

I'll close this as this seems to be a problem not related to the the library.

rodrigoazv commented 3 years ago

I have the same problem, any solution ?

alanyong91 commented 3 years ago

I got the same problem but comments not answering the question

karavadip commented 3 years ago

Same issue, no matter what we do always gives a error TypeError: Cannot read property 'defaults' of undefined

and this error appears at the line where I import the MockAdapter.

I tried importing in 3 ways import { MockAdapter } from 'axios-mock-adapter'; import MockAdapter from 'axios-mock-adapter';and const MockAdapter = require('axios-mock-adapter');

vova42matters commented 2 years ago

In my case I had jest.mock(axios) in test file, removed it and now works as expected