Skip to content

Commit 383f179

Browse files
authoredOct 2, 2024··
fix(browser): throw an error if "@vitest/browser/context" is imported outside of the browser mode (#6570)
1 parent 821400b commit 383f179

File tree

4 files changed

+24
-6
lines changed

4 files changed

+24
-6
lines changed
 

‎packages/browser/context.js

+17-1
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,18 @@
1-
// empty file to not break bundling
21
// Vitest resolves "@vitest/browser/context" as a virtual module instead
2+
3+
// fake exports for static analysis
4+
export const page = null
5+
export const server = null
6+
export const userEvent = null
7+
export const cdp = null
8+
export const commands = null
9+
10+
const pool = globalThis.__vitest_worker__?.ctx?.pool
11+
12+
throw new Error(
13+
// eslint-disable-next-line prefer-template
14+
'@vitest/browser/context can be imported only inside the Browser Mode. '
15+
+ (pool
16+
? `Your test is running in ${pool} pool. Make sure your regular tests are excluded from the "test.include" glob pattern.`
17+
: 'Instead, it was imported outside of Vitest.'),
18+
)

‎packages/vitest/src/create/browser/creator.ts

+2-5
Original file line numberDiff line numberDiff line change
@@ -258,11 +258,8 @@ async function generateWorkspaceFile(options: {
258258
`import { defineWorkspace } from 'vitest/config'`,
259259
'',
260260
'export default defineWorkspace([',
261-
' // This will keep running your existing tests.',
262-
' // If you don\'t need to run those in Node.js anymore,',
263-
' // You can safely remove it from the workspace file',
264-
' // Or move the browser test configuration to the config file.',
265-
` '${relativeRoot}',`,
261+
' // If you want to keep running your existing tests in Node.js, uncomment the next line.',
262+
` // '${relativeRoot}',`,
266263
` {`,
267264
` extends: '${relativeRoot}',`,
268265
` test: {`,
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
import { page } from '@vitest/browser/context'
2+
3+
console.log(page)

‎test/cli/test/__snapshots__/fails.test.ts.snap

+2
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,8 @@ exports[`should fail nested-suite.test.ts > nested-suite.test.ts 1`] = `"Asserti
5858
5959
exports[`should fail no-assertions.test.ts > no-assertions.test.ts 1`] = `"Error: expected any number of assertion, but got none"`;
6060
61+
exports[`should fail node-browser-context.test.ts > node-browser-context.test.ts 1`] = `"Error: @vitest/browser/context can be imported only inside the Browser Mode. Your test is running in forks pool. Make sure your regular tests are excluded from the "test.include" glob pattern."`;
62+
6163
exports[`should fail primitive-error.test.ts > primitive-error.test.ts 1`] = `"Unknown Error: 42"`;
6264
6365
exports[`should fail snapshot-with-not.test.ts > snapshot-with-not.test.ts 1`] = `

0 commit comments

Comments
 (0)
Please sign in to comment.