You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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 happensimport{assert}from'vitest'importcurrentTimefrom'./currentTime.ts'vi.hoisted(()=>{vi.setSystemTime(newDate(2020,1,1,0,0,0))})assert.ok(currentTime.getTime()===newDate(2020,1,1,0,0,0).getTime())
// setup spies for vi.mockimport{assert}from'vitest'import{getTimeFactory}from'./getTime.ts'constmocks=vi.hoisted(()=>{return{getTime: vi.fn()}})vi.mock('./getTime.ts',()=>{return{getTimeFactory: ()=>mocks.getTime,}})mocks.getTime.mockReturnValue(0)constgetTime=getTimeFactory()assert.equals(getTime(),0)
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 andvi.mock
. You can also return values from this function to access them later.Examples:
Alternative
No response
Additional context
No response
Validations
The text was updated successfully, but these errors were encountered: