Skip to content

Commit bdd2e01

Browse files
authored
fix(browser): run in-source tests only when the file itsels is a test file (#8204)
1 parent 66bee83 commit bdd2e01

File tree

3 files changed

+29
-2
lines changed

3 files changed

+29
-2
lines changed

packages/browser/src/node/plugin.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -391,7 +391,7 @@ export default (parentServer: ParentBrowserProject, base = '/'): Plugin[] => {
391391
}
392392
const s = new MagicString(code, { filename })
393393
s.prepend(
394-
`import.meta.vitest = __vitest_index__;\n`,
394+
`Object.defineProperty(import.meta, 'vitest', { get() { return typeof __vitest_worker__ !== 'undefined' && __vitest_worker__.filepath === "${filename.replace(/"/g, '\\"')}" ? __vitest_index__ : undefined } });\n`,
395395
)
396396
return {
397397
code: s.toString(),

test/browser/setup.unit.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ expect.extend({
2222
pass,
2323
message: () => {
2424
const includePattern = checks?.length
25-
? checks.map(check => `✓ |${check}| ${testName}`).join('\n')
25+
? checks.map(check => `✓ |${check.browser}| ${testName}`).join('\n')
2626
: `✓ ${testName}`
2727
return `expected ${pass ? 'not ' : ''}to have "${includePattern}" in the report.\n\nstdout:\n${stdout}`
2828
},

test/browser/specs/runner.test.ts

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -243,6 +243,33 @@ test('viewport', async () => {
243243
})
244244
})
245245

246+
test('in-source tests don\'t run when the module is imported by the test', async () => {
247+
const { stderr, stdout } = await runBrowserTests({}, ['mocking.test.ts'])
248+
expect(stderr).toBe('')
249+
250+
instances.forEach(({ browser }) => {
251+
expect(stdout).toReportPassedTest('test/mocking.test.ts', browser)
252+
})
253+
254+
// there is only one file with one test inside
255+
// if this stops working, it will report twice as much tests
256+
expect(stdout).toContain(`Test Files ${instances.length} passed`)
257+
expect(stdout).toContain(`Tests ${instances.length} passed`)
258+
})
259+
260+
test('in-source tests run correctly when filtered', async () => {
261+
const { stderr, stdout } = await runBrowserTests({}, ['actions.ts'])
262+
expect(stderr).toBe('')
263+
264+
instances.forEach(({ browser }) => {
265+
expect(stdout).toReportPassedTest('src/actions.ts', browser)
266+
})
267+
268+
// there is only one file with one test inside
269+
expect(stdout).toContain(`Test Files ${instances.length} passed`)
270+
expect(stdout).toContain(`Tests ${instances.length} passed`)
271+
})
272+
246273
test.runIf(provider === 'playwright')('timeout hooks', async () => {
247274
const { stderr } = await runBrowserTests({
248275
root: './fixtures/timeout-hooks',

0 commit comments

Comments
 (0)