12

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 example:

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 doesn'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?

1 Answer 1

36

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
//...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.