Skip to content

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

@sheremet-va

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

Metadata

Metadata

Assignees

No one assigned

    Labels

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

    Projects

    Status

    Approved

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions