Skip to content

Commit 1c2b210

Browse files
authoredJan 15, 2025··
fix(api): don't report events during vitest list (#7257)
1 parent 80ce0e1 commit 1c2b210

File tree

16 files changed

+87
-33
lines changed

16 files changed

+87
-33
lines changed
 

‎examples/lit/package.json

+1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
"coverage": "vitest run --coverage",
1111
"dev": "vite",
1212
"test": "vitest",
13+
"list": "vitest list",
1314
"test:ui": "vitest --ui"
1415
},
1516
"dependencies": {

‎examples/lit/vite.config.ts

+3-1
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,10 @@ export default defineConfig({
99
// https://lit.dev/docs/tools/testing/#testing-in-the-browser
1010
browser: {
1111
enabled: true,
12-
name: 'chromium',
1312
provider: 'playwright',
13+
instances: [
14+
{ browser: 'chromium' },
15+
],
1416
},
1517
},
1618
})

‎packages/browser/src/client/client.ts

+2-1
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,10 @@ export const RPC_ID
1212
= PAGE_TYPE === 'orchestrator'
1313
? getBrowserState().sessionId
1414
: getBrowserState().testerId
15+
const METHOD = getBrowserState().method
1516
export const ENTRY_URL = `${
1617
location.protocol === 'https:' ? 'wss:' : 'ws:'
17-
}//${HOST}/__vitest_browser_api__?type=${PAGE_TYPE}&rpcId=${RPC_ID}&sessionId=${getBrowserState().sessionId}&projectName=${getBrowserState().config.name || ''}`
18+
}//${HOST}/__vitest_browser_api__?type=${PAGE_TYPE}&rpcId=${RPC_ID}&sessionId=${getBrowserState().sessionId}&projectName=${getBrowserState().config.name || ''}&method=${METHOD}`
1819

1920
let setCancel = (_: CancelReason) => {}
2021
export const onCancel = new Promise<CancelReason>((resolve) => {

‎packages/browser/src/client/public/esm-client-injector.js

+1
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
sessionId: { __VITEST_SESSION_ID__ },
2828
testerId: { __VITEST_TESTER_ID__ },
2929
provider: { __VITEST_PROVIDER__ },
30+
method: { __VITEST_METHOD__ },
3031
providedContext: { __VITEST_PROVIDED_CONTEXT__ },
3132
};
3233

‎packages/browser/src/client/utils.ts

+1
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,7 @@ export interface BrowserRunnerState {
7474
iframeId?: string
7575
sessionId: string
7676
testerId: string
77+
method: 'run' | 'collect'
7778
runTests?: (tests: string[]) => Promise<void>
7879
createTesters?: (files: string[]) => Promise<void>
7980
cdp?: {

‎packages/browser/src/node/rpc.ts

+34-7
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,13 @@ export function setupBrowserRpc(globalServer: ParentBrowserProject) {
5050
)
5151
}
5252

53+
const method = searchParams.get('method') as 'run' | 'collect'
54+
if (method !== 'run' && method !== 'collect') {
55+
return error(
56+
new Error(`[vitest] Method query in ${request.url} is invalid. Method should be either "run" or "collect".`),
57+
)
58+
}
59+
5360
if (type === 'orchestrator') {
5461
const session = vitest._browserSessions.getSession(sessionId)
5562
// it's possible the session was already resolved by the preview provider
@@ -67,7 +74,7 @@ export function setupBrowserRpc(globalServer: ParentBrowserProject) {
6774
wss.handleUpgrade(request, socket, head, (ws) => {
6875
wss.emit('connection', ws, request)
6976

70-
const rpc = setupClient(project, rpcId, ws)
77+
const rpc = setupClient(project, rpcId, ws, method)
7178
const state = project.browser!.state as BrowserServerState
7279
const clients = type === 'tester' ? state.testers : state.orchestrators
7380
clients.set(rpcId, rpc)
@@ -96,7 +103,7 @@ export function setupBrowserRpc(globalServer: ParentBrowserProject) {
96103
}
97104
}
98105

99-
function setupClient(project: TestProject, rpcId: string, ws: WebSocket) {
106+
function setupClient(project: TestProject, rpcId: string, ws: WebSocket, method: 'run' | 'collect') {
100107
const mockResolver = new ServerMockResolver(globalServer.vite, {
101108
moduleDirectories: project.config.server?.deps?.moduleDirectories,
102109
})
@@ -111,19 +118,39 @@ export function setupBrowserRpc(globalServer: ParentBrowserProject) {
111118
vitest.state.catchError(error, type)
112119
},
113120
async onQueued(file) {
114-
await vitest._testRun.enqueued(project, file)
121+
if (method === 'collect') {
122+
vitest.state.collectFiles(project, [file])
123+
}
124+
else {
125+
await vitest._testRun.enqueued(project, file)
126+
}
115127
},
116128
async onCollected(files) {
117-
await vitest._testRun.collected(project, files)
129+
if (method === 'collect') {
130+
vitest.state.collectFiles(project, files)
131+
}
132+
else {
133+
await vitest._testRun.collected(project, files)
134+
}
118135
},
119136
async onTaskUpdate(packs, events) {
120-
await vitest._testRun.updated(packs, events)
137+
if (method === 'collect') {
138+
vitest.state.updateTasks(packs)
139+
}
140+
else {
141+
await vitest._testRun.updated(packs, events)
142+
}
121143
},
122144
onAfterSuiteRun(meta) {
123145
vitest.coverageProvider?.onAfterSuiteRun(meta)
124146
},
125-
sendLog(log) {
126-
return vitest._testRun.log(log)
147+
async sendLog(log) {
148+
if (method === 'collect') {
149+
vitest.state.updateUserLog(log)
150+
}
151+
else {
152+
await vitest._testRun.log(log)
153+
}
127154
},
128155
resolveSnapshotPath(testPath) {
129156
return vitest.snapshot.resolvePath<ResolveSnapshotPathHandlerContext>(testPath, {

‎packages/browser/src/node/serverOrchestrator.ts

+1
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ export async function resolveOrchestrator(
3636
__VITEST_VITE_CONFIG__: JSON.stringify({
3737
root: browserProject.vite.config.root,
3838
}),
39+
__VITEST_METHOD__: JSON.stringify(session?.method || 'run'),
3940
__VITEST_FILES__: JSON.stringify(files),
4041
__VITEST_TYPE__: '"orchestrator"',
4142
__VITEST_SESSION_ID__: JSON.stringify(sessionId),

‎packages/browser/src/node/serverTester.ts

+2-1
Original file line numberDiff line numberDiff line change
@@ -57,13 +57,14 @@ export async function resolveTester(
5757
: await globalServer.injectorJs
5858

5959
const injector = replacer(injectorJs, {
60-
__VITEST_PROVIDER__: JSON.stringify(project.browser!.provider!.name),
60+
__VITEST_PROVIDER__: JSON.stringify(project.browser!.provider.name),
6161
__VITEST_CONFIG__: JSON.stringify(browserProject.wrapSerializedConfig()),
6262
__VITEST_FILES__: JSON.stringify(files),
6363
__VITEST_VITE_CONFIG__: JSON.stringify({
6464
root: browserProject.vite.config.root,
6565
}),
6666
__VITEST_TYPE__: '"tester"',
67+
__VITEST_METHOD__: JSON.stringify(method),
6768
__VITEST_SESSION_ID__: JSON.stringify(sessionId),
6869
__VITEST_TESTER_ID__: JSON.stringify(crypto.randomUUID()),
6970
__VITEST_PROVIDED_CONTEXT__: JSON.stringify(stringify(project.getProvidedContext())),

‎packages/vitest/src/node/pools/forks.ts

+3-3
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ import { wrapSerializableConfig } from '../../utils/config-helpers'
1717
import { envsOrder, groupFilesByEnv } from '../../utils/test-helpers'
1818
import { createMethodsRPC } from './rpc'
1919

20-
function createChildProcessChannel(project: TestProject) {
20+
function createChildProcessChannel(project: TestProject, collect = false) {
2121
const emitter = new EventEmitter()
2222
const cleanup = () => emitter.removeAllListeners()
2323

@@ -27,7 +27,7 @@ function createChildProcessChannel(project: TestProject) {
2727
postMessage: message => emitter.emit(events.response, message),
2828
}
2929

30-
const rpc = createBirpc<RunnerRPC, RuntimeRPC>(createMethodsRPC(project, { cacheFs: true }), {
30+
const rpc = createBirpc<RunnerRPC, RuntimeRPC>(createMethodsRPC(project, { cacheFs: true, collect }), {
3131
eventNames: ['onCancel'],
3232
serialize: v8.serialize,
3333
deserialize: v => v8.deserialize(Buffer.from(v)),
@@ -109,7 +109,7 @@ export function createForksPool(
109109
const paths = files.map(f => f.filepath)
110110
ctx.state.clearFiles(project, paths)
111111

112-
const { channel, cleanup } = createChildProcessChannel(project)
112+
const { channel, cleanup } = createChildProcessChannel(project, name === 'collect')
113113
const workerId = ++id
114114
const data: ContextRPC = {
115115
pool: 'forks',

‎packages/vitest/src/node/pools/rpc.ts

+26-8
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ const promises = new Map<string, Promise<void>>()
1111

1212
interface MethodsOptions {
1313
cacheFs?: boolean
14+
// do not report files
15+
collect?: boolean
1416
}
1517

1618
export function createMethodsRPC(project: TestProject, options: MethodsOptions = {}): RuntimeRPC {
@@ -74,24 +76,40 @@ export function createMethodsRPC(project: TestProject, options: MethodsOptions =
7476
transform(id, environment) {
7577
return project.vitenode.transformModule(id, environment).catch(handleRollupError)
7678
},
77-
onPathsCollected(paths) {
78-
ctx.state.collectPaths(paths)
79-
return ctx.report('onPathsCollected', paths)
80-
},
8179
async onQueued(file) {
82-
await ctx._testRun.enqueued(project, file)
80+
if (options.collect) {
81+
ctx.state.collectFiles(project, [file])
82+
}
83+
else {
84+
await ctx._testRun.enqueued(project, file)
85+
}
8386
},
8487
async onCollected(files) {
85-
await ctx._testRun.collected(project, files)
88+
if (options.collect) {
89+
ctx.state.collectFiles(project, files)
90+
}
91+
else {
92+
await ctx._testRun.collected(project, files)
93+
}
8694
},
8795
onAfterSuiteRun(meta) {
8896
ctx.coverageProvider?.onAfterSuiteRun(meta)
8997
},
9098
async onTaskUpdate(packs, events) {
91-
await ctx._testRun.updated(packs, events)
99+
if (options.collect) {
100+
ctx.state.updateTasks(packs)
101+
}
102+
else {
103+
await ctx._testRun.updated(packs, events)
104+
}
92105
},
93106
async onUserConsoleLog(log) {
94-
await ctx._testRun.log(log)
107+
if (options.collect) {
108+
ctx.state.updateUserLog(log)
109+
}
110+
else {
111+
await ctx._testRun.log(log)
112+
}
95113
},
96114
onUnhandledError(err, type) {
97115
ctx.state.catchError(err, type)

‎packages/vitest/src/node/pools/threads.ts

+3-3
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,12 @@ import { groupBy } from '../../utils/base'
1616
import { envsOrder, groupFilesByEnv } from '../../utils/test-helpers'
1717
import { createMethodsRPC } from './rpc'
1818

19-
function createWorkerChannel(project: TestProject) {
19+
function createWorkerChannel(project: TestProject, collect: boolean) {
2020
const channel = new MessageChannel()
2121
const port = channel.port2
2222
const workerPort = channel.port1
2323

24-
const rpc = createBirpc<RunnerRPC, RuntimeRPC>(createMethodsRPC(project), {
24+
const rpc = createBirpc<RunnerRPC, RuntimeRPC>(createMethodsRPC(project, { collect }), {
2525
eventNames: ['onCancel'],
2626
post(v) {
2727
port.postMessage(v)
@@ -103,7 +103,7 @@ export function createThreadsPool(
103103
const paths = files.map(f => f.filepath)
104104
ctx.state.clearFiles(project, paths)
105105

106-
const { workerPort, port } = createWorkerChannel(project)
106+
const { workerPort, port } = createWorkerChannel(project, name === 'collect')
107107
const workerId = ++id
108108
const data: WorkerContext = {
109109
pool: 'threads',

‎packages/vitest/src/node/pools/vmForks.ts

+3-3
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ import { createMethodsRPC } from './rpc'
2020

2121
const suppressWarningsPath = resolve(rootDir, './suppress-warnings.cjs')
2222

23-
function createChildProcessChannel(project: TestProject) {
23+
function createChildProcessChannel(project: TestProject, collect: boolean) {
2424
const emitter = new EventEmitter()
2525
const cleanup = () => emitter.removeAllListeners()
2626

@@ -31,7 +31,7 @@ function createChildProcessChannel(project: TestProject) {
3131
}
3232

3333
const rpc = createBirpc<RunnerRPC, RuntimeRPC>(
34-
createMethodsRPC(project, { cacheFs: true }),
34+
createMethodsRPC(project, { cacheFs: true, collect }),
3535
{
3636
eventNames: ['onCancel'],
3737
serialize: v8.serialize,
@@ -117,7 +117,7 @@ export function createVmForksPool(
117117
const paths = files.map(f => f.filepath)
118118
ctx.state.clearFiles(project, paths)
119119

120-
const { channel, cleanup } = createChildProcessChannel(project)
120+
const { channel, cleanup } = createChildProcessChannel(project, name === 'collect')
121121
const workerId = ++id
122122
const data: ContextRPC = {
123123
pool: 'forks',

‎packages/vitest/src/node/pools/vmThreads.ts

+3-3
Original file line numberDiff line numberDiff line change
@@ -19,12 +19,12 @@ import { createMethodsRPC } from './rpc'
1919

2020
const suppressWarningsPath = resolve(rootDir, './suppress-warnings.cjs')
2121

22-
function createWorkerChannel(project: TestProject) {
22+
function createWorkerChannel(project: TestProject, collect: boolean) {
2323
const channel = new MessageChannel()
2424
const port = channel.port2
2525
const workerPort = channel.port1
2626

27-
const rpc = createBirpc<RunnerRPC, RuntimeRPC>(createMethodsRPC(project), {
27+
const rpc = createBirpc<RunnerRPC, RuntimeRPC>(createMethodsRPC(project, { collect }), {
2828
eventNames: ['onCancel'],
2929
post(v) {
3030
port.postMessage(v)
@@ -108,7 +108,7 @@ export function createVmThreadsPool(
108108
const paths = files.map(f => f.filepath)
109109
ctx.state.clearFiles(project, paths)
110110

111-
const { workerPort, port } = createWorkerChannel(project)
111+
const { workerPort, port } = createWorkerChannel(project, name === 'collect')
112112
const workerId = ++id
113113
const data: WorkerContext = {
114114
pool: 'vmThreads',

‎packages/vitest/src/types/rpc.ts

-1
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,6 @@ export interface RuntimeRPC {
3535
force?: boolean
3636
) => Promise<any>
3737

38-
onPathsCollected: (paths: string[]) => void
3938
onUserConsoleLog: (log: UserConsoleLog) => void
4039
onUnhandledError: (err: unknown, type: string) => void
4140
onQueued: (file: File) => void

‎test/cli/fixtures/list/math.test.ts

+2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import { expect, it } from 'vitest'
22

3+
console.log('logging during collection')
4+
35
it('1 plus 1', () => {
46
expect(1 + 1).toBe(2)
57
})

‎test/cli/test/list.test.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -177,7 +177,7 @@ test('correctly prints project name and locations in json report', async () => {
177177
"file": "<root>/fixtures/list/math.test.ts",
178178
"projectName": "custom",
179179
"location": {
180-
"line": 3,
180+
"line": 5,
181181
"column": 1
182182
}
183183
},
@@ -186,7 +186,7 @@ test('correctly prints project name and locations in json report', async () => {
186186
"file": "<root>/fixtures/list/math.test.ts",
187187
"projectName": "custom",
188188
"location": {
189-
"line": 7,
189+
"line": 9,
190190
"column": 1
191191
}
192192
}

0 commit comments

Comments
 (0)
Please sign in to comment.