Skip to content

Commit ca62f37

Browse files
authoredJan 9, 2024
fix(vitest): don't throw SyntaxError when "await vi.hoisted" is used (#4915)
1 parent f99cc31 commit ca62f37

File tree

2 files changed

+28
-3
lines changed

2 files changed

+28
-3
lines changed
 

‎packages/vitest/src/node/hoistMocks.ts

+6-3
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import MagicString from 'magic-string'
2-
import type { CallExpression, Identifier, ImportDeclaration, VariableDeclaration, Node as _Node } from 'estree'
2+
import type { AwaitExpression, CallExpression, Identifier, ImportDeclaration, VariableDeclaration, Node as _Node } from 'estree'
3+
4+
// TODO: should use findNodeBefore, but it's not typed
35
import { findNodeAround } from 'acorn-walk'
46
import type { PluginContext } from 'rollup'
57
import { esmWalker } from '@vitest/utils/ast'
@@ -211,8 +213,9 @@ export function hoistMocks(code: string, id: string, parse: PluginContext['parse
211213
hoistedNodes.push(declarationNode)
212214
}
213215
else {
214-
// hoist "vi.hoisted(() => {})"
215-
hoistedNodes.push(node)
216+
const awaitedExpression = findNodeAround(ast, node.start, 'AwaitExpression')?.node as Positioned<AwaitExpression> | undefined
217+
// hoist "await vi.hoisted(async () => {})" or "vi.hoisted(() => {})"
218+
hoistedNodes.push(awaitedExpression?.argument === node ? awaitedExpression : node)
216219
}
217220
}
218221
}

‎test/core/test/hoisted-async-simple.test.ts

+22
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ import { value } from '../src/rely-on-hoisted'
66
const globalValue = await vi.hoisted(async () => {
77
// @ts-expect-error not typed global
88
globalThis.someGlobalValue = 'globalValue'
9+
// @ts-expect-error not typed global
10+
;(globalThis._order ??= []).push(1)
911
return 'globalValue'
1012
})
1113

@@ -14,6 +16,26 @@ afterAll(() => {
1416
delete globalThis.someGlobalValue
1517
})
1618

19+
// _order is set in the hoisted function before tests are collected
20+
// @ts-expect-error not typed global
21+
expect(globalThis._order).toEqual([1, 2, 3])
22+
1723
it('imported value is equal to returned from hoisted', () => {
1824
expect(value).toBe(globalValue)
1925
})
26+
27+
it('hoists async "vi.hoisted", but leaves the wrapper alone', async () => {
28+
expect.assertions(1)
29+
await (async () => {
30+
expect(1).toBe(1)
31+
vi.hoisted(() => {
32+
// @ts-expect-error not typed global
33+
;(globalThis._order ??= []).push(2)
34+
})
35+
})()
36+
})
37+
38+
await vi.hoisted(async () => {
39+
// @ts-expect-error not typed global
40+
;(globalThis._order ??= []).push(3)
41+
})

0 commit comments

Comments
 (0)
Please sign in to comment.