Skip to content

Commit 2dd3dd8

Browse files
authored
fix: improve runner error when importing outside of test context (#9335)
1 parent b094053 commit 2dd3dd8

File tree

3 files changed

+18
-1
lines changed

3 files changed

+18
-1
lines changed

packages/runner/src/suite.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -187,7 +187,13 @@ let currentTestFilepath: string
187187

188188
function assert(condition: any, message: string) {
189189
if (!condition) {
190-
throw new Error(`Vitest failed to find ${message}. This is a bug in Vitest. Please, open an issue with reproduction.`)
190+
throw new Error(
191+
`Vitest failed to find ${message}. One of the following is possible:`
192+
+ '\n- "vitest" is imported directly without running "vitest" command'
193+
+ '\n- "vitest" is imported inside "globalSetup" (to fix this, use "setupFiles" instead, because "globalSetup" runs in a different context)'
194+
+ '\n- "vitest" is imported inside Vite / Vitest config file'
195+
+ '\n- Otherwise, it might be a Vitest bug. Please report it to https://github.com/vitest-dev/vitest/issues\n',
196+
)
191197
}
192198
}
193199

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import assert from 'node:assert'
2+
// node can import from vitest at any point
3+
import { beforeAll } from 'vitest'
4+
5+
assert.throws(() => {
6+
// some vitest API cannot be used outside of a test context
7+
beforeAll(() => {})
8+
}, /Vitest failed to find the runner. One of the following is possible/)
9+
10+
export default () => {}

test/global-setup/vitest.config.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ export default defineConfig({
2121
'./globalSetup/ts-with-imports.ts',
2222
'./globalSetup/another-vite-instance.ts',
2323
'./globalSetup/update-env.ts',
24+
'./globalSetup/failing.ts',
2425
],
2526
},
2627
})

0 commit comments

Comments
 (0)