question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

TypeError: Cannot read property 'defaults' of undefined

See original GitHub issue

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!

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:6

github_iconTop GitHub Comments

3reactions
Bernardoowcommented, Feb 13, 2021

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

1reaction
himitocommented, Apr 29, 2021

Thank you, @Bernardoow, that fixed my problem too 😄

Read more comments on GitHub >

github_iconTop Results From Across the Web

DataTables: Uncaught TypeError: Cannot read property ...
Uncaught TypeError: Cannot read property 'defaults' of undefined (dataTables.bootstrap.js:20). This causes the pagination controls to not ...
Read more >
Uncaught TypeError: Cannot read property ... - DataTables
i am using datatable with this i am facing that error because of that i can not load data table properly because of...
Read more >
Uncaught TypeError: Cannot read property 'defaults ... - GitHub
It look like you created custom javascript, and I would guess you placed it before jquery or jQuery is not loaded correctly.
Read more >
cannot read properties of undefined (reading 'defaults')
To solve the "Cannot read properties of undefined" error, make sure to insert the JS script tag at the bottom of the body....
Read more >
cannot read property defaults of undefined - Bountysource
with the following.. import axios from 'axios'; import MockAdapter from 'axios-mock-adapter'; const mockAdapter = new MockAdapter(axios); ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found