Skip to content

Utility to automock class instance #4001

@everett1992

Description

@everett1992

Clear and concise description of the problem

As a developer using vitest I want an easy way to create mock instances of a class. While I can us vi.mock('module') to automock the entire file I have to jump thru hoops to get a mock instance, mainly to avoid TypeScript errors

import { Class } from 'module'
vi.mock('module')
// @ts-ignore-error Ignore constructor argument errors
const mockInstance  = new Class()

vi.mock will mock the whole module, so if you wanted another exported value to use the real implementation you need a factory to import the real implementation.

Suggested solution

import { Class } from 'module'
import { vi } from 'vitest'

const mock = vi.mockInstance(Class)

Alternative

No response

Additional context

No response

Validations

Metadata

Metadata

Assignees

No one assigned

    Labels

    p2-nice-to-haveNot breaking anything but nice to have (priority)

    Type

    No type

    Projects

    Status

    Approved

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions