fix(vitest): don't throw SyntaxError when "await vi.hoisted" is used (#4915)

This commit is contained in:
Vladimir 2024-01-09 16:39:27 +01:00 committed by GitHub
parent f99cc3132d
commit ca62f37a88
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 28 additions and 3 deletions

View File

@ -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'
@ -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)
}
}
}

View File

@ -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'
})
@ -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)
})