{return{default:{get:vi.fn()}}});test('fngetInfo()s"> TypeError when using vitest: default is not a function-PHP Chinese Network Q&A
TypeError when using vitest: default is not a function
P粉817354783
P粉817354783 2023-10-29 18:05:17
0
1
575

I'm using vitest to do some unit testing in my vue application. I've written some tests but they fail with the error message: "TypeError: default value is not a function". But I'm not using a function named 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 executenpm run testthe result is as follows:

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| });

info.ts file looks like this:

import { useLoginStore } from "../../store/LoginStore"; import axios from "axios"; // eslint-disable-next-line export async function getInfo(param: string) : Promise { 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?

P粉817354783
P粉817354783

reply all (1)
P粉985686557

Thedefaultattribute in the returned object is not a function (default: {...}). Instead, you will return something like this:

vi.mock('axios', () => ({ default: () => ({ get: vi.fn(), post: vi.fn(), }), }));
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!