Skip to content

Add spy option to vi.mockObject #8284

@rChaoz

Description

@rChaoz

Clear and concise description of the problem

Vitest has great auto-mocking/auto-spying algorithms, which can be used like so:

vi.mock(import("some/module/path"))  // functions do nothing and return undefined
vi.mock(import("some/module/path"), { spy: true })  // functions work normally, but can be manipulated and asserted against

If you want to customize a mocked module, you can do it like so:

vi.mock(import("some/module/path"), async (importOriginal) => {
    const original = await importOriginal()
    const mocked = vi.mockObject(original)
    return {
        ...mocked,
        counter: vi.fn(() => original.counter() + 1)
    }
})

But it is impossible to customize a spied-on module the same way, since there is no spy-version of vi.mockObject().

Suggested solution

vi.mockObject(original, { spy: true })

Note: The function already supports this in its implementation (of course, as it's the one used by vi.mock()):

public mockObject(
object: Record<string | symbol, any>,
moduleType: MockedModuleType = 'automock',
): Record<string | symbol, any> {

export type MockedModuleType = 'automock' | 'autospy' | 'manual' | 'redirect'

It's just not exposed to the end-users.

Validations

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions