Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 489
Liam Arbel Avatar asked Mar 04 '26 08:03

Liam Arbel


1 Answers

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
//...
like image 86
tao Avatar answered Mar 05 '26 22:03

tao



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!