Search code examples
typescriptmockingvuejs3vitest

use "as vi.Mock" for methods from a mocked element when using typescript


When I mock vue-router with Jest, and want to mock the return value of an internal method, typescript doesn't understand that the inner method has become a mock, and can be treated as such.

For exapmle:

import { useRoute } from 'vue-router';
jest.mock('vue-router');
useRoute .mockReturnValue({

That won't work. So the trick is to instruct typescript to treat it as a mock

const useRouteNew = useRoute as jest.Mock;
useRouteNew.mockReturnValue({

So with Jest that works, but I'm trying to imitate that with Vitest:

import { vi } from "vitest";
import { useRoute } from 'vue-router';
vi.mock('vue-router');
const useRouteNew = useRoute as vi.Mock;
useRouteNew.mockReturnValue({

That deosn't work. Here typescript complains that it "can't find the 'vi' namespace"

Any idea what I can do here with Vitest to get it to work?


Solution

  • The vi import from 'vitest' is not a namespace, it's a const alias of a class (VitestUtils), which doesn't contain any types or interfaces.

    All Vitest interfaces and types, including Mock, are exported by 'vitest' directly:

    import { vi, Mock } from 'vitest'
    import { useRoute } from 'vue-router'
    vi.mock('vue-router')
    const mockedUseRoute = useRoute as Mock
    //...