Skip to content

Commit

Permalink
fix(vitest): don't throw SyntaxError when "await vi.hoisted" is used (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
sheremet-va authored Jan 9, 2024
1 parent f99cc31 commit ca62f37
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
9 changes: 6 additions & 3 deletions packages/vitest/src/node/hoistMocks.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import MagicString from 'magic-string'
import type { CallExpression, Identifier, ImportDeclaration, VariableDeclaration, Node as _Node } from 'estree'
import type { AwaitExpression, CallExpression, Identifier, ImportDeclaration, VariableDeclaration, Node as _Node } from 'estree'

// TODO: should use findNodeBefore, but it's not typed
import { findNodeAround } from 'acorn-walk'
import type { PluginContext } from 'rollup'
import { esmWalker } from '@vitest/utils/ast'
Expand Down Expand Up @@ -211,8 +213,9 @@ export function hoistMocks(code: string, id: string, parse: PluginContext['parse
hoistedNodes.push(declarationNode)
}
else {
// hoist "vi.hoisted(() => {})"
hoistedNodes.push(node)
const awaitedExpression = findNodeAround(ast, node.start, 'AwaitExpression')?.node as Positioned<AwaitExpression> | undefined
// hoist "await vi.hoisted(async () => {})" or "vi.hoisted(() => {})"
hoistedNodes.push(awaitedExpression?.argument === node ? awaitedExpression : node)
}
}
}
Expand Down
22 changes: 22 additions & 0 deletions test/core/test/hoisted-async-simple.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import { value } from '../src/rely-on-hoisted'
const globalValue = await vi.hoisted(async () => {
// @ts-expect-error not typed global
globalThis.someGlobalValue = 'globalValue'
// @ts-expect-error not typed global
;(globalThis._order ??= []).push(1)
return 'globalValue'
})

Expand All @@ -14,6 +16,26 @@ afterAll(() => {
delete globalThis.someGlobalValue
})

// _order is set in the hoisted function before tests are collected
// @ts-expect-error not typed global
expect(globalThis._order).toEqual([1, 2, 3])

it('imported value is equal to returned from hoisted', () => {
expect(value).toBe(globalValue)
})

it('hoists async "vi.hoisted", but leaves the wrapper alone', async () => {
expect.assertions(1)
await (async () => {
expect(1).toBe(1)
vi.hoisted(() => {
// @ts-expect-error not typed global
;(globalThis._order ??= []).push(2)
})
})()
})

await vi.hoisted(async () => {
// @ts-expect-error not typed global
;(globalThis._order ??= []).push(3)
})

0 comments on commit ca62f37

Please sign in to comment.