Mocking Axios and Reusing Mocks Across Test Files in Vitest

258 Views Asked by At

I am facing an issue when trying to mock Axios for my tests and reusing these mocks across different test files. The primary goal is to mock Axios utilizing vi.mock from vitest, but an error is thrown, hindering the process. The error message displayed is: Error: Parse failure: Unexpected token (20:0) pinpointing to a particular line in the mockAxios.ts file.

// mockAxios.ts
import { vi } from "vitest";

export const mocks = vi.hoisted(() => ({
    get: vi.fn(),
}));

vi.mock('axios', async () => {
    const actual: any = await vi.importActual("axios");
    return {
        default: {
            ...actual.default,
            create: vi.fn(() => ({
                ...actual.default.create(),
                get: mocks.get,  
            })),
        },
    };
});  // This is line 20

I have used vi.mock to mock Axios, as illustrated in the snippet above. Here's how I am utilizing the mock in a test file:

// test-file.ts
import * as mocks from "@/_tests/mocks/mockAxios";
//... rest of the imports

describe("GET", () => {
    const mockData = [ { _id: '123', name: 'Client A' } ]

    it("should return a list of clients", async () => {
        mocks.mocks.get.mockResolvedValueOnce({ data: mockData });
        //... rest of the test code
    })

})

I expected vi.mock to mock Axios successfully, allowing me to reuse mocks across different test files. However, I am confronted with a parse error at line 20 in mockAxios.ts.

vitest version: vitest/0.34.6.

0

There are 0 best solutions below