vitest/prefer-vi-mocked

May 24, 2026 ยท View on GitHub

๐Ÿ“ Require vi.mocked() over fn as Mock.

โš ๏ธ This rule warns in the ๐ŸŒ all config.

๐Ÿ”ง This rule is automatically fixable by the --fix CLI option.

When working with mocks of functions using Vitest, it's recommended to use the vi.mocked() helper function to properly type the mocked functions. This rule enforces the use of vi.mocked() for better type safety and readability.

Restricted types:

  • Mock
  • MockedFunction
  • MockedClass
  • MockedObject

Rule details

The following patterns are warnings:

;(foo as Mock).mockReturnValue(1)
const mock = (foo as Mock).mockReturnValue(1)
;(foo as unknown as Mock).mockReturnValue(1)
;(Obj.foo as Mock).mockReturnValue(1)
;([].foo as Mock).mockReturnValue(1)

The following patterns are not warnings:

vi.mocked(foo).mockReturnValue(1)
const mock = vi.mocked(foo).mockReturnValue(1)
vi.mocked(Obj.foo).mockReturnValue(1)
vi.mocked([].foo).mockReturnValue(1)