-
-
Notifications
You must be signed in to change notification settings - Fork 424
Expand file tree
/
Copy pathlighthouse-setup.cjs
More file actions
73 lines (62 loc) · 2.39 KB
/
lighthouse-setup.cjs
File metadata and controls
73 lines (62 loc) · 2.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/**
* Lighthouse CI puppeteer setup script.
*
* Sets the color mode (light/dark) before running accessibility audits
* and intercepts client-side API requests using the same fixture data
* as the Playwright E2E tests.
*
* The color mode is determined by the LIGHTHOUSE_COLOR_MODE environment variable.
* If not set, defaults to 'dark'.
*
* Request interception uses CDP (Chrome DevTools Protocol) at the browser level
* so it applies to all pages Lighthouse opens, not just the setup page.
*/
const mockRoutes = require('./test/fixtures/mock-routes.cjs')
module.exports = async function setup(browser, { url }) {
const colorMode = process.env.LIGHTHOUSE_COLOR_MODE || 'dark'
// Set up browser-level request interception via CDP.
// This ensures mocking applies to pages Lighthouse creates after setup.
setupBrowserRequestInterception(browser)
const page = await browser.newPage()
// Set localStorage before navigating so @nuxtjs/color-mode picks it up
await page.evaluateOnNewDocument(mode => {
localStorage.setItem('npmx-color-mode', mode)
}, colorMode)
// Navigate and wait for DOM only - Lighthouse will do its own full load
await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 60000 })
// Close the page - Lighthouse will open its own with localStorage already set
await page.close()
}
/**
* Set up request interception on every new page target the browser creates.
* Uses Puppeteer's page-level request interception, applied automatically
* to each new page via the 'targetcreated' event.
*
* @param {import('puppeteer').Browser} browser
*/
function setupBrowserRequestInterception(browser) {
browser.on('targetcreated', async target => {
if (target.type() !== 'page') return
try {
const page = await target.page()
if (!page) return
await page.setRequestInterception(true)
page.on('request', request => {
const requestUrl = request.url()
const result = mockRoutes.matchRoute(requestUrl)
if (result) {
request.respond({
status: result.response.status,
contentType: result.response.contentType,
body: result.response.body,
})
} else {
request.continue()
}
})
} catch {
// Target may have been closed before we could set up interception.
// This is expected for transient targets like service workers.
}
})
}