Skip to content

Chrome DevTools for coding agents

test: migrate lighthouse emulation restore test to unit test (#2725)

Mahesh Singhe3d9e791b7ca
diff --git a/src/third_party/index.ts b/src/third_party/index.ts
index 27e13460..6371c1da 100644
--- a/src/third_party/index.ts
+++ b/src/third_party/index.ts
@@ -79,15 +79,18 @@ import {
generateReport as generateReportImpl,
} from './lighthouse-devtools-mcp-bundle.js';
-export const snapshot = snapshotImpl as (
- page: Page,
- options: {flags?: Flags},
-) => Promise<RunnerResult>;
-export const navigation = navigationImpl as (
- page: Page,
- url: string,
- options: {flags?: Flags},
-) => Promise<RunnerResult>;
+export const lighthouseRunner = {
+ snapshot: snapshotImpl as (
+ page: Page,
+ options: {flags?: Flags},
+ ) => Promise<RunnerResult>,
+ navigation: navigationImpl as (
+ page: Page,
+ url: string,
+ options: {flags?: Flags},
+ ) => Promise<RunnerResult>,
+};
+
export const generateReport = generateReportImpl as (
lhr: Result,
format: string,
diff --git a/src/tools/lighthouse.ts b/src/tools/lighthouse.ts
index 3a08967f..9cb7579e 100644
--- a/src/tools/lighthouse.ts
+++ b/src/tools/lighthouse.ts
@@ -7,8 +7,7 @@
import path from 'node:path';
import {
- snapshot,
- navigation,
+ lighthouseRunner,
generateReport,
zod,
type Flags,
@@ -92,11 +91,15 @@ export const lighthouseAudit = definePageTool({
let result: RunnerResult | undefined;
try {
if (mode === 'navigation') {
- result = await navigation(page.pptrPage, page.pptrPage.url(), {
- flags,
- });
+ result = await lighthouseRunner.navigation(
+ page.pptrPage,
+ page.pptrPage.url(),
+ {
+ flags,
+ },
+ );
} else {
- result = await snapshot(page.pptrPage, {
+ result = await lighthouseRunner.snapshot(page.pptrPage, {
flags,
});
}
diff --git a/tests/McpPage.test.ts b/tests/McpPage.test.ts
index addca551..24bdfb03 100644
--- a/tests/McpPage.test.ts
+++ b/tests/McpPage.test.ts
@@ -529,6 +529,54 @@ describe('McpPage', () => {
});
});
+ describe('restoreEmulation()', () => {
+ afterEach(() => {
+ sinon.restore();
+ });
+
+ it('re-applies previously configured viewport emulation', async () => {
+ const {mcpPage, pptrPage} = createMcpPage();
+ await mcpPage.emulate({
+ viewport: {
+ width: 400,
+ height: 400,
+ deviceScaleFactor: 1,
+ isMobile: false,
+ hasTouch: false,
+ isLandscape: false,
+ },
+ });
+ sinon.assert.calledOnce(pptrPage.setViewport);
+
+ await mcpPage.restoreEmulation();
+
+ sinon.assert.calledTwice(pptrPage.setViewport);
+ sinon.assert.calledWithExactly(pptrPage.setViewport.secondCall, {
+ width: 400,
+ height: 400,
+ deviceScaleFactor: 1,
+ isMobile: false,
+ hasTouch: false,
+ isLandscape: false,
+ });
+ });
+
+ it('re-applies previously configured network and cpu throttling emulation', async () => {
+ const {mcpPage, pptrPage} = createMcpPage();
+ await mcpPage.emulate({
+ networkConditions: 'Slow 3G',
+ cpuThrottlingRate: 4,
+ });
+ sinon.assert.calledOnce(pptrPage.emulateNetworkConditions);
+ sinon.assert.calledOnce(pptrPage.emulateCPUThrottling);
+
+ await mcpPage.restoreEmulation();
+
+ sinon.assert.calledTwice(pptrPage.emulateNetworkConditions);
+ sinon.assert.calledTwice(pptrPage.emulateCPUThrottling);
+ });
+ });
+
describe('waitForTextOnPage()', () => {
it('finds text on the page', async () => {
await withMcpContext(async (_response, context) => {
diff --git a/tests/mocks.ts b/tests/mocks.ts
index b52c6af1..98c747d7 100644
--- a/tests/mocks.ts
+++ b/tests/mocks.ts
@@ -34,7 +34,12 @@ import {
CdpPage,
DevTools,
} from '../src/third_party/index.js';
-import type {Extension, Page} from '../src/third_party/index.js';
+import type {
+ Extension,
+ Page,
+ Result,
+ RunnerResult,
+} from '../src/third_party/index.js';
export type MockMcpPage = sinon.SinonStubbedInstance<McpPage> & {
pptrPage: sinon.SinonStubbedInstance<Page>;
@@ -185,6 +190,20 @@ export function createHandlerMocks(): {
return {page, context, response};
}
+export function createMockRunnerResult(): RunnerResult {
+ const lhr = {
+ mainDocumentUrl: 'http://localhost',
+ categories: {},
+ audits: {},
+ timing: {total: 0},
+ };
+ return {
+ lhr: lhr as unknown as Result,
+ report: '',
+ artifacts: {} as unknown as RunnerResult['artifacts'],
+ };
+}
+
type RuleOrigin = 'regular' | 'user-agent' | 'injected' | 'inspector';
function isBackendNodeId(
diff --git a/tests/tools/lighthouse.test.ts b/tests/tools/lighthouse.test.ts
index 272d6ec4..5a2edadc 100644
--- a/tests/tools/lighthouse.test.ts
+++ b/tests/tools/lighthouse.test.ts
@@ -8,14 +8,22 @@ import assert from 'node:assert/strict';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
-import {describe, it} from 'node:test';
+import {afterEach, describe, it} from 'node:test';
+import sinon from 'sinon';
+
+import {lighthouseRunner} from '../../src/third_party/index.js';
import {lighthouseAudit} from '../../src/tools/lighthouse.js';
import {resolveCanonicalPath} from '../../src/utils/files.js';
+import {createHandlerMocks, createMockRunnerResult} from '../mocks.js';
import {serverHooks} from '../server.js';
import {html, withMcpContext} from '../utils.js';
describe('lighthouse', () => {
+ afterEach(() => {
+ sinon.restore();
+ });
+
const server = serverHooks();
describe('lighthouse_audit', () => {
it('runs Lighthouse audit by default (navigation, desktop)', async () => {
@@ -54,68 +62,50 @@ describe('lighthouse', () => {
});
it('restores emulation', async () => {
- server.addHtmlRoute('/test-mobile', html`<div>Test Mobile</div>`);
+ const {page, context, response} = createHandlerMocks();
+ context.saveTemporaryFile.resolves({filepath: 'report.json'});
+ sinon
+ .stub(lighthouseRunner, 'snapshot')
+ .resolves(createMockRunnerResult());
- await withMcpContext(async (response, context) => {
- const page = context.getSelectedMcpPage().pptrPage;
- await page.goto(server.getRoute('/test-mobile'));
- await context.getSelectedMcpPage().emulate({
- viewport: {
- width: 400,
- height: 400,
- deviceScaleFactor: 1,
- hasTouch: true,
+ await lighthouseAudit.handler(
+ {
+ params: {
+ mode: 'snapshot',
+ device: 'mobile',
},
- });
+ page,
+ },
+ response,
+ context,
+ );
- {
- const viewportData = await page.evaluate(() => {
- return {
- width: window.innerWidth,
- height: window.innerHeight,
- deviceScaleFactor: window.devicePixelRatio,
- hasTouch: navigator.maxTouchPoints > 0,
- };
- });
-
- assert.deepStrictEqual(viewportData, {
- width: 400,
- height: 400,
- deviceScaleFactor: 1,
- hasTouch: true,
- });
- }
+ sinon.assert.calledOnceWithExactly(page.restoreEmulation);
+ });
- await lighthouseAudit.handler(
- {
- params: {
- mode: 'snapshot',
- device: 'mobile',
+ it('restores emulation even when audit fails', async () => {
+ const {page, context, response} = createHandlerMocks();
+ sinon
+ .stub(lighthouseRunner, 'snapshot')
+ .rejects(new Error('Audit failed'));
+
+ await assert.rejects(
+ () =>
+ lighthouseAudit.handler(
+ {
+ params: {
+ mode: 'snapshot',
+ device: 'mobile',
+ },
+ page,
},
- page: context.getSelectedMcpPage(),
- },
- response,
- context,
- );
+ response,
+ context,
+ ),
+ {message: 'Audit failed'},
+ );
- {
- const viewportData = await page.evaluate(() => {
- return {
- width: window.innerWidth,
- height: window.innerHeight,
- deviceScaleFactor: window.devicePixelRatio,
- hasTouch: navigator.maxTouchPoints > 0,
- };
- });
-
- assert.deepStrictEqual(viewportData, {
- width: 400,
- height: 400,
- deviceScaleFactor: 1,
- hasTouch: true,
- });
- }
- });
+ sinon.assert.calledOnceWithExactly(page.restoreEmulation);
});
it('runs Lighthouse in snapshot mode with mobile device', async () => {