Skip to content

Commit 0c502bc

Browse files
authored
perf(browser): reuse cached modules during vitest run (#11914)
1 parent 47fb992 commit 0c502bc

4 files changed

Lines changed: 235 additions & 10 deletions

File tree

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

Lines changed: 35 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,8 @@ export {
6060
} from './utils'
6161

6262
const versionRegexp = /(?:\?|&)v=\w{8}/
63+
// the url of a factory mock's shim, see `getManualMockUrl` in @vitest/mocker
64+
const manualMockRegexp = /\/@id\/__x00__vitest-mock:/
6365

6466
const optimizedChunkFiles = new WeakMap<object, Set<string>>()
6567

@@ -267,30 +269,53 @@ body {
267269
)
268270
}
269271

272+
// a persistent context or the preview provider keeps the browser's cache after
273+
// the process exits, and every instance can set its own provider
274+
const cacheOutlivesProcess = () =>
275+
[parentServer.config, ...Array.from(parentServer.children, (child) => child.config)].some(
276+
(config) =>
277+
(config.browser.provider?.options as { persistentContext?: unknown } | undefined)
278+
?.persistentContext || config.browser.provider?.name === 'preview',
279+
)
280+
270281
// vitest's own dist files only change with the vitest version and
271282
// browser contexts don't outlive the process, so there is no reason
272-
// to revalidate them in every tester iframe. Skipped for persistent
273-
// contexts and preview providers — their disk cache would survive a vitest upgrade
274-
const persistentContext = (
275-
parentServer.config.browser.provider?.options as { persistentContext?: unknown } | undefined
276-
)?.persistentContext
277-
const immutablePrefixes =
278-
persistentContext || parentServer.config.browser.provider?.name === 'preview'
279-
? []
280-
: ['/__vitest_browser__/', `/@fs${vitestDist}`, `/@fs${distRoot}`]
283+
// to revalidate them in every tester iframe. Skipped when the cache
284+
// outlives the process — it would survive a vitest upgrade
285+
const immutablePrefixes = ['/__vitest_browser__/', `/@fs${vitestDist}`, `/@fs${distRoot}`]
281286

282287
// request interception serves a mocked dependency at the original URL,
283288
// so a cached original would never reach the mock; import map mocks
284289
// have their own URLs and keep Vite's immutable caching
285290
const interceptsMocks = () =>
286291
Array.from(parentServer.children).some((child) => !child.state.usesImportMaps(child.config))
287292

293+
// modules don't change during `vitest run`, so a new tester iframe can reuse
294+
// the cached ones instead of revalidating each of them
295+
const cacheRunModules = !parentServer.vitest.config.watch
296+
288297
server.middlewares.use((req, res, next) => {
289298
const url = req.url
290299
if (url) {
291-
if (immutablePrefixes.some((prefix) => url.startsWith(prefix))) {
300+
if (
301+
!cacheOutlivesProcess() &&
302+
immutablePrefixes.some((prefix) => url.startsWith(prefix))
303+
) {
292304
pinCacheControl(res, 'public,max-age=31536000,immutable')
293305
}
306+
// a cached original would bypass a mock served by request interception, and
307+
// the shim of a factory mock can export different names in every test file
308+
else if (
309+
cacheRunModules &&
310+
req.method === 'GET' &&
311+
req.headers['sec-fetch-dest'] === 'script' &&
312+
!versionRegexp.test(url) &&
313+
!manualMockRegexp.test(url) &&
314+
!cacheOutlivesProcess() &&
315+
!interceptsMocks()
316+
) {
317+
pinCacheControl(res, 'private,max-age=31536000')
318+
}
294319
// 9000 mega head move
295320
// Vite always caches optimized dependencies, but users might mock
296321
// them in _some_ tests, while keeping original modules in others;

‎packages/vitest/src/node/core.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,7 @@ export class Vitest {
170170
*/
171171
_rootBrowserParent: ParentProjectBrowser | undefined
172172
/** @internal */ _browserSessions = new BrowserSessions()
173+
/** @internal */ _browserCacheStale = false
173174
/** @internal */ reporters: Reporter[] = []
174175
/** @internal */ runner!: ModuleRunner
175176
/** @internal */ _testRun: TestRun
@@ -1647,6 +1648,11 @@ export class Vitest {
16471648
*/
16481649
public invalidateFile(filepath: string): void {
16491650
this.specifications.invalidateDocblock(filepath)
1651+
// during `vitest run` the browser takes modules from its HTTP cache without asking the
1652+
// server, so the browser pool opens new contexts before the next run
1653+
if (!this.config.watch) {
1654+
this._browserCacheStale = true
1655+
}
16501656
this.projects.forEach(({ vite }) => {
16511657
const environments = Object.values(vite.environments)
16521658

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

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,21 @@ export function createBrowserPool(vitest: Vitest): BrowserPool {
205205
cancel()
206206
})
207207

208+
// an invalidated module keeps its url, so a browser context that cached it
209+
// in an earlier run would serve the old code
210+
if (vitest._browserCacheStale) {
211+
vitest._browserCacheStale = false
212+
// runs don't overlap (`runFiles` waits for the previous one), so no worker should be
213+
// active here; the check only keeps a running worker from being stopped
214+
Array.from(workers.values())
215+
.filter((worker) => !activeWorkers.has(worker))
216+
.forEach((worker) => stopWorker(worker))
217+
await Promise.all(exitPromises)
218+
if (isCancelled) {
219+
return
220+
}
221+
}
222+
208223
const groupedFiles = await groupSpecifications(specs)
209224

210225
const tasks = await Promise.all(
Lines changed: 179 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,179 @@
1+
import type { Plugin } from 'vite'
2+
import { mkdtempSync, rmSync } from 'node:fs'
3+
import { tmpdir } from 'node:os'
4+
import { playwright } from '@vitest/browser-playwright'
5+
import { join } from 'pathe'
6+
import { expect, onTestFinished, test } from 'vitest'
7+
import { createVitest } from 'vitest/node'
8+
import { createFile, useTmpFS } from '../../test-utils'
9+
import { instances, provider, runInlineBrowserTests } from './utils'
10+
11+
const CACHED = 'private,max-age=31536000'
12+
13+
function recordResponses(matches: (pathname: string) => boolean = (path) => path === '/shared.ts') {
14+
const responses: { status: number; cacheControl?: string }[] = []
15+
const plugin: Plugin = {
16+
name: 'record-responses',
17+
configureServer(server) {
18+
server.middlewares.use((req, res, next) => {
19+
res.on('finish', () => {
20+
if (req.url && matches(new URL(req.url, 'http://localhost').pathname)) {
21+
responses.push({
22+
status: res.statusCode,
23+
cacheControl: res.getHeader('cache-control') as string | undefined,
24+
})
25+
}
26+
})
27+
next()
28+
})
29+
},
30+
}
31+
return { plugin, responses }
32+
}
33+
34+
const sharedModuleTests = {
35+
'shared.ts': `export const value = 'shared'`,
36+
'first.test.ts': `
37+
import { expect, test } from 'vitest'
38+
import { value } from './shared'
39+
test('imports the shared module', () => {
40+
expect(value).toBe('shared')
41+
})
42+
`,
43+
'second.test.ts': `
44+
import { expect, test } from 'vitest'
45+
import { value } from './shared'
46+
test('imports the shared module', () => {
47+
expect(value).toBe('shared')
48+
})
49+
`,
50+
}
51+
52+
test.runIf(provider.name === 'playwright')(
53+
'tester iframes reuse cached modules during the run',
54+
async () => {
55+
const { plugin, responses } = recordResponses()
56+
const { stderr } = await runInlineBrowserTests(sharedModuleTests, {
57+
fileParallelism: false,
58+
browser: { instances: [instances[0]] },
59+
$viteConfig: { plugins: [plugin] },
60+
})
61+
62+
expect(stderr).toReportNoErrors()
63+
// the second test file takes the module from the cache
64+
expect(responses).toEqual([{ status: 200, cacheControl: CACHED }])
65+
},
66+
)
67+
68+
test.runIf(provider.name === 'playwright')(
69+
'modules are revalidated when mocks are served by request interception',
70+
async () => {
71+
const { plugin, responses } = recordResponses()
72+
const { stderr } = await runInlineBrowserTests(sharedModuleTests, {
73+
fileParallelism: false,
74+
browser: { instances: [instances[0]], importMapMocks: false },
75+
$viteConfig: { plugins: [plugin] },
76+
})
77+
78+
expect(stderr).toReportNoErrors()
79+
// the second test file revalidates the module
80+
expect(responses).toEqual([{ status: 200, cacheControl: 'no-cache' }, { status: 304 }])
81+
},
82+
)
83+
84+
test.runIf(provider.name === 'playwright')(
85+
'a persistent context of any instance keeps modules revalidated',
86+
async () => {
87+
const userDataDir = mkdtempSync(join(tmpdir(), 'vitest-run-module-cache-'))
88+
onTestFinished(() => rmSync(userDataDir, { recursive: true, force: true }))
89+
const { plugin, responses } = recordResponses()
90+
const { stderr } = await runInlineBrowserTests(sharedModuleTests, {
91+
fileParallelism: false,
92+
browser: {
93+
instances: [
94+
{ ...instances[0], name: 'a', provider: playwright() },
95+
// its cache would keep the modules for the next `vitest run`
96+
{ ...instances[0], name: 'b', provider: playwright({ persistentContext: userDataDir }) },
97+
],
98+
},
99+
$viteConfig: { plugins: [plugin] },
100+
})
101+
102+
expect(stderr).toReportNoErrors()
103+
expect(responses.length).toBeGreaterThan(0)
104+
expect(responses.filter((response) => response.cacheControl === CACHED)).toEqual([])
105+
},
106+
)
107+
108+
test.runIf(provider.name === 'playwright')(
109+
'the shims of factory mocks are revalidated',
110+
async () => {
111+
const { plugin, responses } = recordResponses((path) =>
112+
path.includes('/@id/__x00__vitest-mock:'),
113+
)
114+
const testFile = (name: string) => `
115+
import { expect, test, vi } from 'vitest'
116+
import { value } from './dep'
117+
vi.mock('./dep', () => ({ value: '${name}' }))
118+
test('imports the mock', () => {
119+
expect(value).toBe('${name}')
120+
})
121+
`
122+
const { stderr } = await runInlineBrowserTests(
123+
{
124+
'dep.ts': `export const value = 'dep'`,
125+
'first.test.ts': testFile('first'),
126+
'second.test.ts': testFile('second'),
127+
},
128+
{
129+
fileParallelism: false,
130+
browser: { instances: [instances[0]] },
131+
$viteConfig: { plugins: [plugin] },
132+
},
133+
)
134+
135+
expect(stderr).toReportNoErrors()
136+
// the shim takes its exports from the factory of the current test file
137+
expect(responses.length).toBeGreaterThan(0)
138+
expect(responses.filter((response) => response.cacheControl === CACHED)).toEqual([])
139+
},
140+
)
141+
142+
test.runIf(provider.name === 'playwright')(
143+
'an invalidated module is read again on the next run',
144+
async () => {
145+
const { root } = useTmpFS({
146+
'value.ts': `export const value = 'before'`,
147+
'basic.test.ts': `
148+
import { test, vi } from 'vitest'
149+
import { value } from './value'
150+
test('logs the value', async () => {
151+
const actual = await vi.importActual('./value')
152+
console.log(\`value: \${value}, actual: \${actual.value}\`)
153+
})
154+
`,
155+
})
156+
const values: string[] = []
157+
const vitest = await createVitest('test', {
158+
root,
159+
watch: false,
160+
reporters: [
161+
{
162+
onUserConsoleLog(log) {
163+
values.push(log.content.trim())
164+
},
165+
},
166+
],
167+
browser: { enabled: true, headless: true, provider, instances: [instances[0]] },
168+
})
169+
onTestFinished(() => vitest.close())
170+
171+
await vitest.start()
172+
createFile(join(root, 'value.ts'), `export const value = 'after'`)
173+
vitest.invalidateFile(join(root, 'value.ts'))
174+
await vitest.rerunFiles()
175+
176+
// the browser context of the first run has the old module in its cache
177+
expect(values).toEqual(['value: before, actual: before', 'value: after, actual: after'])
178+
},
179+
)

0 commit comments

Comments
 (0)