Skip to content

Chrome DevTools for coding agents

test: add sinon mock utils and emulate tool unit tests (#2641)

Mahesh Singh086299a69e6d
diff --git a/package.json b/package.json
index 2fc894f4..e3c6c327 100644
--- a/package.json
+++ b/package.json
@@ -15,7 +15,7 @@
"build": "tsc && node scripts/post-build.ts",
"typecheck": "tsc --noEmit",
"format": "eslint --cache --fix . && prettier --write --cache .",
- "check-format": "eslint --cache . && prettier --check --cache .;",
+ "check-format": "eslint --cache . && prettier --check --cache .",
"gen": "npm run build && npm run cli:generate && npm run docs:generate && npm run update-metrics && npm run format",
"docs:generate": "node scripts/generate-docs.ts",
"start": "npm run build && node build/src/bin/chrome-devtools-mcp.js",
diff --git a/src/third_party/index.ts b/src/third_party/index.ts
index dfb779ac..d7b49695 100644
--- a/src/third_party/index.ts
+++ b/src/third_party/index.ts
@@ -44,7 +44,7 @@ export {
export {default as puppeteer} from 'puppeteer-core';
export type * from 'puppeteer-core';
export {PipeTransport} from 'puppeteer-core/internal/node/PipeTransport.js';
-export type {CdpPage} from 'puppeteer-core/internal/cdp/Page.js';
+export {CdpPage} from 'puppeteer-core/internal/cdp/Page.js';
export type {CdpWebWorker} from 'puppeteer-core/internal/cdp/WebWorker.js';
export type {Realm} from 'puppeteer-core/internal/api/Realm.js';
export type {JSONSchema7, JSONSchema7Definition} from 'json-schema';
diff --git a/tests/McpPage.test.ts b/tests/McpPage.test.ts
index 4574d79a..1289aa9e 100644
--- a/tests/McpPage.test.ts
+++ b/tests/McpPage.test.ts
@@ -5,10 +5,17 @@
*/
import assert from 'node:assert';
-import {describe, it} from 'node:test';
+import {afterEach, describe, it} from 'node:test';
+import sinon from 'sinon';
+
+import {McpPage} from '../src/McpPage.js';
import {replaceHtmlElementsWithUids} from '../src/McpPage.js';
+import {Locator} from '../src/third_party/index.js';
import type {JSONSchema7Definition} from '../src/third_party/index.js';
+import type {Page} from '../src/third_party/index.js';
+import {createMockPuppeteerPage} from './mocks.js';
+
import {withMcpContext} from './utils.js';
describe('replaceHtmlElementsWithUids', () => {
@@ -274,4 +281,104 @@ describe('McpPage', () => {
assert.ok(handle.disposed);
});
});
+
+ describe('emulate()', () => {
+ afterEach(() => {
+ sinon.restore();
+ });
+
+ function createMcpPage() {
+ const pptrPage = createMockPuppeteerPage();
+ const mcpPage = new McpPage(pptrPage as unknown as Page, 1, {
+ hasNetworkBlockOrAllowlist: false,
+ locatorClass: Locator,
+ });
+ return {mcpPage, pptrPage};
+ }
+
+ it('calls emulateNetworkConditions with the predefined condition', async () => {
+ const {mcpPage, pptrPage} = createMcpPage();
+ await mcpPage.emulate({networkConditions: 'Slow 3G'});
+ assert.strictEqual(mcpPage.networkConditions, 'Slow 3G');
+ sinon.assert.calledOnceWithExactly(pptrPage.emulateNetworkConditions, {
+ download: 50000,
+ upload: 50000,
+ latency: 2000,
+ });
+ });
+
+ it('calls emulateNetworkConditions(null) when networkConditions is omitted', async () => {
+ const {mcpPage, pptrPage} = createMcpPage();
+ await mcpPage.emulate({networkConditions: 'Slow 3G'});
+ await mcpPage.emulate({});
+ assert.strictEqual(mcpPage.networkConditions, null);
+ sinon.assert.calledWithExactly(
+ pptrPage.emulateNetworkConditions.secondCall,
+ null,
+ );
+ });
+
+ it('does not call emulateNetworkConditions for unknown values', async () => {
+ const {mcpPage, pptrPage} = createMcpPage();
+ await mcpPage.emulate({networkConditions: 'Slow 11G'});
+ assert.strictEqual(mcpPage.networkConditions, null);
+ sinon.assert.notCalled(pptrPage.emulateNetworkConditions);
+ });
+
+ it('calls emulateCPUThrottling with the given rate', async () => {
+ const {mcpPage, pptrPage} = createMcpPage();
+ await mcpPage.emulate({cpuThrottlingRate: 4});
+ assert.strictEqual(mcpPage.cpuThrottlingRate, 4);
+ sinon.assert.calledOnceWithExactly(pptrPage.emulateCPUThrottling, 4);
+ });
+
+ it('calls emulateCPUThrottling(1) to reset throttling', async () => {
+ const {mcpPage, pptrPage} = createMcpPage();
+ await mcpPage.emulate({cpuThrottlingRate: 4});
+ await mcpPage.emulate({cpuThrottlingRate: 1});
+ assert.strictEqual(mcpPage.cpuThrottlingRate, 1);
+ sinon.assert.calledWithExactly(
+ pptrPage.emulateCPUThrottling.secondCall,
+ 1,
+ );
+ });
+
+ it('calls setUserAgent with the given user agent', async () => {
+ const {mcpPage, pptrPage} = createMcpPage();
+ await mcpPage.emulate({userAgent: 'TestUA/1.0'});
+ assert.strictEqual(mcpPage.userAgent, 'TestUA/1.0');
+ sinon.assert.calledOnceWithExactly(pptrPage.setUserAgent, {
+ userAgent: 'TestUA/1.0',
+ });
+ });
+
+ it('calls setUserAgent with undefined to clear the user agent', async () => {
+ const {mcpPage, pptrPage} = createMcpPage();
+ await mcpPage.emulate({userAgent: 'TestUA/1.0'});
+ await mcpPage.emulate({userAgent: ''});
+ assert.strictEqual(mcpPage.userAgent, null);
+ sinon.assert.calledWithExactly(pptrPage.setUserAgent.secondCall, {
+ userAgent: undefined,
+ });
+ });
+
+ it('calls emulateMediaFeatures with dark color scheme', async () => {
+ const {mcpPage, pptrPage} = createMcpPage();
+ await mcpPage.emulate({colorScheme: 'dark'});
+ assert.strictEqual(mcpPage.colorScheme, 'dark');
+ sinon.assert.calledOnceWithExactly(pptrPage.emulateMediaFeatures, [
+ {name: 'prefers-color-scheme', value: 'dark'},
+ ]);
+ });
+
+ it('calls emulateMediaFeatures with empty string to reset color scheme', async () => {
+ const {mcpPage, pptrPage} = createMcpPage();
+ await mcpPage.emulate({colorScheme: 'dark'});
+ await mcpPage.emulate({colorScheme: 'auto'});
+ assert.strictEqual(mcpPage.colorScheme, null);
+ sinon.assert.calledWithExactly(pptrPage.emulateMediaFeatures.secondCall, [
+ {name: 'prefers-color-scheme', value: ''},
+ ]);
+ });
+ });
});
diff --git a/tests/mocks.ts b/tests/mocks.ts
new file mode 100644
index 00000000..8bf2c9e6
--- /dev/null
+++ b/tests/mocks.ts
@@ -0,0 +1,130 @@
+/**
+ * @license
+ * Copyright 2026 Google LLC
+ * SPDX-License-Identifier: Apache-2.0
+ */
+
+/**
+ * Sinon-based mock factories for McpPage, McpContext, McpResponse and
+ * the underlying Puppeteer Page.
+ *
+ * Uses sinon.createStubInstance() so all methods are automatically stubbed
+ * from the real class prototype — no hand-rolled interface definitions needed.
+ *
+ * Usage example:
+ *
+ * const page = createMockMcpPage();
+ * const context = createMockMcpContext({selectedPage: page});
+ * const response = createMockMcpResponse();
+ *
+ * await myTool.handler({params: {networkConditions: 'Slow 3G'}, page}, response, context);
+ *
+ * sinon.assert.calledOnceWithExactly(page.emulate, {networkConditions: 'Slow 3G'});
+ */
+
+import type {Frame} from 'puppeteer-core';
+import sinon from 'sinon';
+
+import {McpContext} from '../src/McpContext.js';
+import {McpPage} from '../src/McpPage.js';
+import {McpResponse} from '../src/McpResponse.js';
+import {CdpPage} from '../src/third_party/index.js';
+import type {Page} from '../src/third_party/index.js';
+
+export type MockMcpPage = sinon.SinonStubbedInstance<McpPage>;
+export type MockMcpContext = sinon.SinonStubbedInstance<McpContext>;
+export type MockMcpResponse = sinon.SinonStubbedInstance<McpResponse>;
+
+/**
+ * A minimal event emitter used to back mocked `on`/`off`/`emit` methods on
+ * Puppeteer objects (Page, CDPSession, Browser) so tests can trigger events
+ * synchronously without a real browser.
+ */
+export function mockListener() {
+ const listeners: Record<
+ string | symbol | number,
+ Array<(data: unknown) => void>
+ > = {};
+ return {
+ on(eventName: string | symbol | number, listener: (data: unknown) => void) {
+ const arr = listeners[eventName];
+ if (arr) {
+ arr.push(listener);
+ } else {
+ listeners[eventName] = [listener];
+ }
+ },
+ off(
+ _eventName: string | symbol | number,
+ _listener?: (data: unknown) => void,
+ ) {
+ // no-op
+ },
+ emit(eventName: string | symbol | number, data?: unknown) {
+ for (const listener of listeners[eventName] ?? []) {
+ listener(data);
+ }
+ },
+ };
+}
+
+export function createMockPuppeteerPage(): sinon.SinonStubbedInstance<Page> {
+ const page = sinon.createStubInstance(
+ CdpPage,
+ ) as unknown as sinon.SinonStubbedInstance<Page>;
+
+ // mainFrame() must return a stable object so tests can pass it back into
+ // page.emit('framenavigated', mainFrame) and have it recognized as the
+ // same frame instance across calls.
+ page.mainFrame.returns({} as Frame);
+
+ // _client() is a private internal Puppeteer API used by ConsoleCollector
+ // in the McpPage constructor. Not on the CdpPage prototype, so added
+ // explicitly. It needs real on/off/emit behavior so tests can trigger CDP
+ // events directly via cdpSession.emit(...).
+ const cdpListener = mockListener();
+ const cdpSession = {
+ on: sinon.stub().callsFake(cdpListener.on),
+ off: sinon.stub().callsFake(cdpListener.off),
+ send: sinon.stub().resolves({}),
+ target: sinon.stub().returns({_targetId: '<mock>'}),
+ emit: cdpListener.emit,
+ };
+ // @ts-expect-error internal API
+ page._client = sinon.stub().returns(cdpSession);
+
+ return page;
+}
+
+export function createMockMcpPage(): MockMcpPage {
+ return sinon.createStubInstance(McpPage);
+}
+
+export function createMockMcpContext(
+ options: {selectedPage?: MockMcpPage} = {},
+): MockMcpContext {
+ const context = sinon.createStubInstance(McpContext);
+ const page = options.selectedPage ?? createMockMcpPage();
+ context.getSelectedMcpPage.returns(page satisfies McpPage);
+ return context;
+}
+
+export function createMockMcpResponse(): MockMcpResponse {
+ return sinon.createStubInstance(McpResponse);
+}
+
+/**
+ * Convenience helper — creates a mock page, context and response in one call.
+ *
+ * const {page, context, response} = createHandlerMocks();
+ */
+export function createHandlerMocks(): {
+ page: MockMcpPage;
+ context: MockMcpContext;
+ response: MockMcpResponse;
+} {
+ const page = createMockMcpPage();
+ const context = createMockMcpContext({selectedPage: page});
+ const response = createMockMcpResponse();
+ return {page, context, response};
+}
diff --git a/tests/tools/emulation.test.ts b/tests/tools/emulation.test.ts
index 0956c59c..fb704f90 100644
--- a/tests/tools/emulation.test.ts
+++ b/tests/tools/emulation.test.ts
@@ -8,12 +8,15 @@ import assert from 'node:assert';
import type {IncomingHttpHeaders} from 'node:http';
import {beforeEach, describe, it, mock} from 'node:test';
+import sinon from 'sinon';
+
import {emulate} from '../../src/tools/emulation.js';
import {
geolocationTransform,
viewportTransform,
} from '../../src/tools/ToolDefinition.js';
import {serverHooks} from '../server.js';
+import {createHandlerMocks} from '../mocks.js';
import {html, withMcpContext} from '../utils.js';
describe('emulation', () => {
@@ -122,75 +125,45 @@ describe('emulation', () => {
describe('network', () => {
it('emulates offline network conditions', async () => {
- await withMcpContext(async (response, context) => {
- await emulate.handler(
- {
- params: {
- networkConditions: 'Offline',
- },
- page: context.getSelectedMcpPage(),
- },
- response,
- context,
- );
-
- assert.strictEqual(
- context.getSelectedMcpPage().networkConditions,
- 'Offline',
- );
+ const {page, context, response} = createHandlerMocks();
+ await emulate.handler(
+ {params: {networkConditions: 'Offline'}, page},
+ response,
+ context,
+ );
+ sinon.assert.calledOnceWithExactly(page.emulate, {
+ networkConditions: 'Offline',
});
});
- it('emulates network throttling when the throttling option is valid', async () => {
- await withMcpContext(async (response, context) => {
- await emulate.handler(
- {
- params: {
- networkConditions: 'Slow 3G',
- },
- page: context.getSelectedMcpPage(),
- },
- response,
- context,
- );
- assert.strictEqual(
- context.getSelectedMcpPage().networkConditions,
- 'Slow 3G',
- );
+ it('emulates network throttling when the throttling option is valid', async () => {
+ const {page, context, response} = createHandlerMocks();
+ await emulate.handler(
+ {params: {networkConditions: 'Slow 3G'}, page},
+ response,
+ context,
+ );
+ sinon.assert.calledOnceWithExactly(page.emulate, {
+ networkConditions: 'Slow 3G',
});
});
- it('disables network emulation', async () => {
- await withMcpContext(async (response, context) => {
- await emulate.handler(
- {
- params: {},
- page: context.getSelectedMcpPage(),
- },
- response,
- context,
- );
-
- assert.strictEqual(
- context.getSelectedMcpPage().networkConditions,
- null,
- );
- });
+ it('disables network emulation when networkConditions is omitted', async () => {
+ const {page, context, response} = createHandlerMocks();
+ await emulate.handler({params: {}, page}, response, context);
+ sinon.assert.calledOnceWithExactly(page.emulate, {});
});
it('does not set throttling when the network throttling is not one of the predefined options', async () => {
await withMcpContext(async (response, context) => {
await emulate.handler(
{
- params: {
- networkConditions: 'Slow 11G',
- },
+ params: {networkConditions: 'Slow 11G'},
page: context.getSelectedMcpPage(),
},
response,
context,
);
-
assert.strictEqual(
context.getSelectedMcpPage().networkConditions,
null,
@@ -199,50 +172,27 @@ describe('emulation', () => {
});
it('report correctly for the currently selected page', async () => {
- await withMcpContext(async (response, context) => {
- await emulate.handler(
- {
- params: {
- networkConditions: 'Slow 3G',
- },
- page: context.getSelectedMcpPage(),
- },
- response,
- context,
- );
-
- assert.strictEqual(
- context.getSelectedMcpPage().networkConditions,
- 'Slow 3G',
- );
-
- const page = await context.newPage();
- context.selectPage(page);
-
- assert.strictEqual(
- context.getSelectedMcpPage().networkConditions,
- null,
- );
+ const {page, context, response} = createHandlerMocks();
+ await emulate.handler(
+ {params: {networkConditions: 'Slow 3G'}, page},
+ response,
+ context,
+ );
+ sinon.assert.calledOnceWithExactly(page.emulate, {
+ networkConditions: 'Slow 3G',
});
});
});
describe('cpu', () => {
it('emulates cpu throttling when the rate is valid (1-20x)', async () => {
- await withMcpContext(async (response, context) => {
- await emulate.handler(
- {
- params: {
- cpuThrottlingRate: 4,
- },
- page: context.getSelectedMcpPage(),
- },
- response,
- context,
- );
-
- assert.strictEqual(context.getSelectedMcpPage().cpuThrottlingRate, 4);
- });
+ const {page, context, response} = createHandlerMocks();
+ await emulate.handler(
+ {params: {cpuThrottlingRate: 4}, page},
+ response,
+ context,
+ );
+ sinon.assert.calledOnceWithExactly(page.emulate, {cpuThrottlingRate: 4});
});
it('applies cpu throttling to secondary session', async () => {
@@ -275,46 +225,24 @@ describe('emulation', () => {
});
});
- it('disables cpu throttling', async () => {
- await withMcpContext(async (response, context) => {
- await context.getSelectedMcpPage().emulate({
- cpuThrottlingRate: 4,
- });
- await emulate.handler(
- {
- params: {
- cpuThrottlingRate: 1,
- },
- page: context.getSelectedMcpPage(),
- },
- response,
- context,
- );
-
- assert.strictEqual(context.getSelectedMcpPage().cpuThrottlingRate, 1);
- });
+ it('disables cpu throttling when rate is 1', async () => {
+ const {page, context, response} = createHandlerMocks();
+ await emulate.handler(
+ {params: {cpuThrottlingRate: 1}, page},
+ response,
+ context,
+ );
+ sinon.assert.calledOnceWithExactly(page.emulate, {cpuThrottlingRate: 1});
});
it('report correctly for the currently selected page', async () => {
- await withMcpContext(async (response, context) => {
- await emulate.handler(
- {
- params: {
- cpuThrottlingRate: 4,
- },
- page: context.getSelectedMcpPage(),
- },
- response,
- context,
- );
-
- assert.strictEqual(context.getSelectedMcpPage().cpuThrottlingRate, 4);
-
- const page = await context.newPage();
- context.selectPage(page);
-
- assert.strictEqual(context.getSelectedMcpPage().cpuThrottlingRate, 1);
- });
+ const {page, context, response} = createHandlerMocks();
+ await emulate.handler(
+ {params: {cpuThrottlingRate: 4}, page},
+ response,
+ context,
+ );
+ sinon.assert.calledOnceWithExactly(page.emulate, {cpuThrottlingRate: 4});
});
});
diff --git a/tests/utils.ts b/tests/utils.ts
index 95046fd0..2aa34907 100644
--- a/tests/utils.ts
+++ b/tests/utils.ts
@@ -29,6 +29,8 @@ import {TextSnapshot} from '../src/TextSnapshot.js';
import {DevTools} from '../src/third_party/index.js';
import {stableIdSymbol} from '../src/utils/id.js';
+import {createMockPuppeteerPage, mockListener} from './mocks.js';
+
export function assertNoServiceWorkerReported(targets: Target[], id: string) {
const target = targets.find(target => {
return target.url().includes(id) && target.type() === 'service_worker';
@@ -373,53 +375,24 @@ export function getMockAggregatedIssue(): sinon.SinonStubbedInstance<DevTools.Ag
return mockAggregatedIssue;
}
-export function mockListener() {
- const listeners: Record<string, Array<(data: unknown) => void>> = {};
- return {
- on(eventName: string, listener: (data: unknown) => void) {
- if (listeners[eventName]) {
- listeners[eventName].push(listener);
- } else {
- listeners[eventName] = [listener];
- }
- },
- off(_eventName: string, _listener: (data: unknown) => void) {
- // no-op
- },
- emit(eventName: string, data: unknown) {
- for (const listener of listeners[eventName] ?? []) {
- listener(data);
- }
- },
- };
-}
-
-export function getMockPage(): Page {
- const mainFrame = {} as Frame;
- const cdpSession = {
- ...mockListener(),
- send: () => {
- // no-op
- },
- target: () => ({_targetId: '<mock target ID>'}),
- };
- return {
- mainFrame() {
- return mainFrame;
- },
- ...mockListener(),
- // @ts-expect-error internal API.
- _client() {
- return cdpSession;
- },
- } satisfies Page;
-}
-
export function getMockBrowser(options?: {
process?: ChildProcess | null;
wsEndpoint?: string;
}): Browser {
- const pages = [getMockPage()];
+ const page = createMockPuppeteerPage();
+ const listener = mockListener();
+ page.on.callsFake((eventName, handler) => {
+ listener.on(eventName, handler);
+ return page;
+ });
+ page.off.callsFake((eventName, handler) => {
+ if (handler) {
+ listener.off(eventName, handler);
+ }
+ return page;
+ });
+ (page as unknown as {emit: typeof listener.emit}).emit = listener.emit;
+ const pages = [page as unknown as Page];
return {
process() {
return options?.process ?? null;