Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce vi.hoisted to run code before imports and vi.mock #3228

Closed
4 tasks done
sheremet-va opened this issue Apr 21, 2023 · 0 comments · Fixed by #3258
Closed
4 tasks done

Introduce vi.hoisted to run code before imports and vi.mock #3228

sheremet-va opened this issue Apr 21, 2023 · 0 comments · Fixed by #3258
Labels
enhancement New feature or request

Comments

@sheremet-va
Copy link
Member

sheremet-va commented Apr 21, 2023

Clear and concise description of the problem

All imports in ESM are hoisted to the top of the file, so any code that is defined before that run after imports and all its side effects. Vitest also has vi.mock which behaves in a similar manner, but it is hoisted even before the imports.

Sometimes there are reasons to run code before import happens (for example, to mock time). It also would be nice to have access to variables in vi.mock to later reuse them in tests (like setting up a spy).

Suggested solution

Introduce vi.hoisted method. It receives a callback that will run before all the imports and vi.mock. You can also return values from this function to access them later.

Examples:

// mock time before import happens
import { assert } from 'vitest'
import currentTime from './currentTime.ts'

vi.hoisted(() => {
  vi.setSystemTime(new Date(2020, 1, 1, 0, 0, 0))
})

assert.ok(currentTime.getTime() === new Date(2020, 1, 1, 0, 0, 0).getTime())
// setup spies for vi.mock
import { assert } from 'vitest'
import { getTimeFactory } from './getTime.ts'

const mocks = vi.hoisted(() => {
  return { getTime: vi.fn() }
})

vi.mock('./getTime.ts', () => {
  return {
    getTimeFactory: () => mocks.getTime,
  }
})

mocks.getTime.mockReturnValue(0)
const getTime = getTimeFactory()
assert.equals(getTime(), 0)

Alternative

No response

Additional context

No response

Validations

@sheremet-va sheremet-va added the enhancement New feature or request label Apr 21, 2023
@github-actions github-actions bot locked and limited conversation to collaborators Jun 3, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant