ctimmerm / axios-mock-adapter

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

TypeError: Cannot read property 'defaults' of undefined #268

Closed chalist closed 4 years ago

chalist commented 4 years ago

I got this error for importing axios-mock-adapter:

FAIL  src/Components/Service/__tests__/api.service.test.js
  ● Test suite failed to run

    TypeError: Cannot read property 'defaults' of undefined

      1 | import axios from "axios";
      2 | 
    > 3 | const MockAdapter = require("axios-mock-adapter");
        |                     ^
      4 | const mock = new MockAdapter(axios);
      5 | 
      6 | import { randomString } from "@/Components/Tools/StringTools";

      at Object.<anonymous> (node_modules/axios-mock-adapter/src/utils.js:8:25)
      at Object.<anonymous> (node_modules/axios-mock-adapter/src/handle_request.js:3:13)
      at Object.<anonymous> (node_modules/axios-mock-adapter/src/index.js:3:21)
      at Object.<anonymous> (src/Components/Service/__tests__/api.service.test.js:3:21)

I searched, but I cant find anything about this error.

api.service.test.js:

import axios from "axios";

const MockAdapter = require("axios-mock-adapter");
const mocker = new MockAdapter(axios);

import { randomString } from "@/Components/Tools/StringTools";
const data = [{ id: 1, name: "John Smith", token: "fjhgyklasjdhnaksdbnasdbajsdghabsdhjgtavsudytqwve897a6sdbaishdgb" }];

jest.mock("axios");

import { ApiService } from "../api.service";

describe("fetchData", () => {
    beforeEach(() => {});

    it("ApiService interceptors check for redirect according to error status", async () => {
        axios.get.mockImplementation(() => {
            return Promise.resolve({ data: data });
        });

        const router = {
            push: jest.fn(),
        };

        expect(router.push).toHaveBeenCalled();
    });

    it("ApiService init() method has been called for set axios baseUrl", async () => {
        const baseURL = randomString(10);
        process.env.VUE_APP_URL = baseURL;

        ApiService.init();

        expect(axios.defaults.baseURL).toBe(baseURL);
    });

    it("ApiService query() method has been called with reject/resolve", async () => {
        const url = randomString(10);
        ApiService.setHeader = jest.fn();

        axios.get.mockImplementation(() => {
            return Promise.resolve({ data: data });
        });

        await ApiService.query(`/${url}`, url).then(response => {
            expect(ApiService.setHeader).toHaveBeenCalled();
            expect(axios.get).toHaveBeenCalledWith(`/${url}`, url);
            expect(response.data).toStrictEqual(data);
        });

        const errorMessage = randomString(20);
        axios.get.mockImplementation(() => {
            return Promise.reject(new Error(errorMessage));
        });
        expect(ApiService.query()).rejects.toThrow(errorMessage);
    });

    it("ApiService get() method has been called with reject/resolve", async () => {
        const url = randomString(10);
        axios.get.mockImplementation(() => {
            return Promise.resolve({ data: data });
        });

        await ApiService.get(`/${url}`, url).then(response => {
            expect(axios.get).toHaveBeenCalledWith(`/${url}/${url}`);
            expect(response.data).toStrictEqual(data);
        });

        const errorMessage = randomString(20);
        axios.get.mockImplementation(() => {
            return Promise.reject(new Error(errorMessage));
        });
        expect(ApiService.get()).rejects.toThrow(errorMessage);
    });

    it("ApiService post() method has been called with reject/resolve", async () => {
        const url = randomString(10);

        axios.post.mockImplementation(() => {
            return Promise.resolve({ data: data });
        });
        await ApiService.post(`/${url}`, url, url).then(response => {
            expect(axios.post).toHaveBeenCalledWith(`/${url}`, url, url);
            expect(response.data).toStrictEqual(data);
        });

        const errorMessage = randomString(20);
        axios.post.mockImplementation(() => {
            return Promise.reject(new Error(errorMessage));
        });
        expect(ApiService.post()).rejects.toThrow(errorMessage);
    });
});

I don't know where I make mistake!

zanonnicola commented 4 years ago

Could be that you have imported the libraries incorrectly. Try:

import axios from 'axios'
import MockAdapter from 'axios-mock-adapter'
const mockAdapter = new MockAdapter(axios)

import { randomString } from "@/Components/Tools/StringTools";
const data = [{ id: 1, name: "John Smith", token: "fjhgyklasjdhnaksdbnasdbajsdghabsdhjgtavsudytqwve897a6sdbaishdgb" }];

// jest.mock("axios"); --> no need to do this

import { ApiService } from "../api.service";
jose920405 commented 3 years ago
import axios from 'axios'
import MockAdapter from 'axios-mock-adapter'
const mockAdapter = new MockAdapter(axios)

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",.

Bernardoow commented 3 years ago

It is happening with me too.

Bernardoow commented 3 years ago

I fixed my problemn. It was because I wrote the code jest.mock('axios'). I removed this and everything works normally.

himito commented 3 years ago

Thank you, @Bernardoow, that fixed my problem too :D

sfkhakimov commented 3 years ago

@jose920405 Tell me, did you manage to solve the problem?