Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: default is not a function when using vitest

I'm using vitest to do some unit tests in my vue application. I've written some tests but they fail with the error message: 'TypeError: default is not a function'. But I do not use a function called default() in my code.

import getInfo from './info';

vi.mock('axios', () => {
    return {
        default: {
            get: vi.fn()
        }
    }
});

test('fn getInfo() should request api with axios.get url', async () => {
    const spyAxios = vi.spyOn(axios, 'get');
    await getInfo('1234');
    expect(spyAxios).toHaveBeenCalledWith(`${process.env.VUE_APP_API_BASE_URL}`);
});

If I then execute npm run test the result is the following:

 FAIL  src/api/info/info.test.js > fn getInfo() should request api with axios.get url
TypeError: default is not a function
 ❯ src/api/info/info.test.js:61:22
     59| test('fn getInfo() should request api with axios.get url', async () => {
     60|     const spyAxios = vi.spyOn(axios, 'get');
     61|     await getInfo('1234');
       |                  ^
     62|     expect(spyAxios).toHaveBeenCalledWith(`${process.env.VUE_APP_API_BASE_URL}`);
     63| });

The info.ts file looks like the following:

import { useLoginStore } from "../../store/LoginStore";
import axios from "axios";

// eslint-disable-next-line
export async function getInfo(param: string) : Promise<any> {
    const loginStore = useLoginStore();
    axios.defaults.headers.common = {'Authorization': `Bearer ${loginStore.accessToken}`};
    
    const request = await axios.get(
        process.env.VUE_APP_API_BASE_URL
    );

    if (request?.status == 200) {
        return request.data;
    }
    else {
        return null;
    }
}

Does anyone know what's going on here?

like image 251
Florian Avatar asked Apr 25 '26 03:04

Florian


2 Answers

The default attribute in your return object is not a function (default: {...}). Instead, you would return something like this:

vi.mock('axios', () => ({
  default: () => ({
    get: vi.fn(),
    post: vi.fn(),
  }),
}));
like image 77
Mark Swardstrom Avatar answered Apr 27 '26 23:04

Mark Swardstrom


In your test, instead of this:

import getInfo from './info';

Do this:

import { getInfo } from './info';

Problem

Your test is importing getInfo as default from info.ts. But in your info.ts you're not exporting getInfo as default. As such, you should import the function as a named import, putting it in curly braces, not as a default import as you currently have.

like image 29
Shant Dashjian Avatar answered Apr 27 '26 22:04

Shant Dashjian



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!