Skip to content

Print a warning if vi.mock or vi.hoisted is not called at the top level #9288

Description

@sheremet-va

Clear and concise description of the problem

vi.mock and vi.hoisted are compiler hints, they escape their scope during transformation. Consider this:

import './add.js'

test('mock only inside this test', () => {
  if(condition) {
    vi.mock('./add.js')
  }
})

test('not mocked here', () => {
  //
})

The generated code actually looks like this:

vi.mock('./add.js')
await import('./add.js')

test('mock only inside this test', () => {
  if(condition) {
  }
})

test('not mocked here', () => {
  //
})

This is extensively documented, but many people do not understand how these methods work at a glance.

Suggested solution

Show a warning if vi.mock or vi.hoisted declaration is not defined at the top level of the file. In one of the next majors, we can throw an error and refuse to transform the file.

Alternative

No response

Additional context

I am also considering if we should refuse to transform vi.mock/vi.hoisted outside of the test file/setup file.

Validations

Activity

  1. moved this to Approved in Team Boardon Dec 18, 2025
  2. undefinedIsMyLife commented on Dec 21, 2025

    @undefinedIsMyLife

    Hi @sheremet-va 👋
    This makes sense and should help clarify how vi.mock / vi.hoisted behave during transform.

    I’d be happy to work on adding a warning when they’re not called at the top level, following the approach described here. If that sounds good, I can open a PR for review.

  3. locked and limited conversation to collaborators on Jan 31, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

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

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions