Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.
TypeScript automationchromechromiume2e-testingelectronend-to-end-testingfirefoxjavascriptplaywrighttesttest-automationtestingtesting-toolswebwebkit
test(dashboard): add basic dashboard app tests (#39635)
Yury Semikhatsky2fca5c7aedd9
diff --git a/packages/playwright-core/src/tools/cli-client/program.ts b/packages/playwright-core/src/tools/cli-client/program.tsindex 5b19dd7b99..54cabf1f7e 100644--- a/packages/playwright-core/src/tools/cli-client/program.ts+++ b/packages/playwright-core/src/tools/cli-client/program.ts@@ -173,7 +173,7 @@ export async function program(options?: { embedderVersion?: string}) {await installBrowser();return;case 'show': {- const daemonScript = require.resolve('../../devtools/devtoolsApp.js');+ const daemonScript = require.resolve('../dashboard/dashboardApp.js');const child = spawn(process.execPath, [daemonScript], {detached: true,stdio: 'ignore',diff --git a/packages/playwright-core/src/tools/dashboard/dashboardApp.ts b/packages/playwright-core/src/tools/dashboard/dashboardApp.tsindex 97122d4934..5c7690b1fe 100644--- a/packages/playwright-core/src/tools/dashboard/dashboardApp.ts+++ b/packages/playwright-core/src/tools/dashboard/dashboardApp.ts@@ -183,15 +183,17 @@ async function openDashboardApp(): Promise<api.Page> {async function launchApp(appName: string) {const channel = findChromiumChannelBestEffort('javascript');+ const debugPort = parseInt(process.env.PLAYWRIGHT_DASHBOARD_DEBUG_PORT!, 10) || undefined;const context = await chromium.launchPersistentContext('', {ignoreDefaultArgs: ['--enable-automation'],channel,- headless: false,+ headless: debugPort !== undefined,args: ['--app=data:text/html,','--test-type=',`--window-size=1280,800`,`--window-position=100,100`,+ ...(debugPort !== undefined ? [`--remote-debugging-port=${debugPort}`] : []),],viewport: null,});@@ -281,13 +283,16 @@ async function acquireSingleton(): Promise<net.Server> {async function main() {let server: net.Server | undefined;process.on('exit', () => server?.close());- try {- server = await acquireSingleton();- } catch {- return;+ const underTest = !!process.env.PLAYWRIGHT_DASHBOARD_DEBUG_PORT;+ if (!underTest) {+ try {+ server = await acquireSingleton();+ } catch {+ return;+ }}const page = await openDashboardApp();- server.on('connection', socket => {+ server?.on('connection', socket => {socket.on('data', data => {if (data.toString() === 'bringToFront')page?.bringToFront().catch(() => {});diff --git a/packages/playwright-core/src/tools/mcp/browserFactory.ts b/packages/playwright-core/src/tools/mcp/browserFactory.tsindex 06d927e2af..d4ed8634d3 100644--- a/packages/playwright-core/src/tools/mcp/browserFactory.ts+++ b/packages/playwright-core/src/tools/mcp/browserFactory.ts@@ -143,7 +143,7 @@ async function injectCdpPort(browserConfig: FullConfig['browser']) {async function findFreePort(): Promise<number> {return new Promise((resolve, reject) => {const server = net.createServer();- server.listen(0, () => {+ server.listen(0, '127.0.0.1', () => {const { port } = server.address() as net.AddressInfo;server.close(() => resolve(port));});diff --git a/tests/config/commonFixtures.ts b/tests/config/commonFixtures.tsindex 0c7fef0db2..126759165a 100644--- a/tests/config/commonFixtures.ts+++ b/tests/config/commonFixtures.ts@@ -236,6 +236,7 @@ export function killProcessGroup(pid: number, signal: 'SIGINT' | 'SIGKILL' = 'SIexport type CommonFixtures = {childProcess: (params: TestChildParams) => TestChildProcess;waitForPort: (port: number) => Promise<void>;+ findFreePort: () => Promise<number>;};export type CommonWorkerFixtures = {@@ -289,6 +290,20 @@ export const commonFixtures: Fixtures<CommonFixtures, CommonWorkerFixtures> = {});token.canceled = true;},++ findFreePort: async ({}, use) => {+ await use(async () => {+ return new Promise((resolve, reject) => {+ const server = net.createServer();+ server.listen(0, '127.0.0.1', () => {+ const { port } = server.address() as net.AddressInfo;+ server.close(() => resolve(port));+ });+ server.on('error', reject);++ });+ });+ },};export function countTimes(s: string, sub: string): number {diff --git a/tests/mcp/cli-fixtures.ts b/tests/mcp/cli-fixtures.tsindex 51ed349802..3738e6ccec 100644--- a/tests/mcp/cli-fixtures.ts+++ b/tests/mcp/cli-fixtures.ts@@ -17,14 +17,18 @@import fs from 'fs';import path from 'path';+import { chromium } from 'playwright-core';+import { test as baseTest } from './fixtures';import { killProcessGroup } from '../config/commonFixtures';+import type { Page } from 'playwright-core';import type { CommonFixtures } from '../config/commonFixtures';export { expect } from './fixtures';export const test = baseTest.extend<{cliEnv: Record<string, string>,+ openDashboard: () => Promise<Page>,cli: (...args: any[]) => Promise<{output: string,error: string,@@ -37,6 +41,25 @@ export const test = baseTest.extend<{cliEnv: async ({}, use) => {await use(cliEnv());},+ openDashboard: async ({ cli, waitForPort, findFreePort }, use) => {+ const dashboards = [];+ await use(async () => {+ const debugPort = await findFreePort();+ await cli('show', { env: { PLAYWRIGHT_DASHBOARD_DEBUG_PORT: String(debugPort) } });+ await waitForPort(debugPort);+ const browser = await chromium.connectOverCDP(`http://127.0.0.1:${debugPort}`);+ const dashboard = browser.contexts()[0].pages()[0];+ dashboards.push({ dashboard, browser });+ return dashboard;+ });+ for (const { dashboard, browser } of dashboards) {+ await Promise.all([+ // Closing the page should close the browser.+ new Promise(r => browser.on('disconnected', r)),+ dashboard.close()+ ]);+ }+ },cli: async ({ mcpBrowser, mcpHeadless, childProcess }, use) => {const sessions: { name: string, pid: number }[] = [];await fs.promises.mkdir(test.info().outputPath('.playwright'), { recursive: true });diff --git a/tests/mcp/dashboard.spec.ts b/tests/mcp/dashboard.spec.tsnew file mode 100644index 0000000000..7445d85246--- /dev/null+++ b/tests/mcp/dashboard.spec.ts@@ -0,0 +1,80 @@+/**+ * Copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { test, expect } from './cli-fixtures';++test.beforeEach(({}, testInfo) => {+ process.env.PLAYWRIGHT_SERVER_REGISTRY = testInfo.outputPath('registry');+});++test('should show browser session chip', async ({ cli, server, openDashboard }) => {+ await cli('open', server.EMPTY_PAGE);++ const dashboard = await openDashboard();+ const chips = dashboard.locator('.session-chip');+ await expect(chips).toHaveCount(1);+});++test('should show devtools sidebar', async ({ cli, server, openDashboard, mcpBrowser }) => {+ test.skip(!['chrome', 'msedge', 'chromium'].includes(mcpBrowser!), 'DevTools sidebar requires CDP, only available in Chromium');++ await cli('open', server.EMPTY_PAGE);++ const dashboard = await openDashboard();+ await dashboard.locator('.session-chip').click();++ const devToolsButton = dashboard.locator('button.nav-btn[title="Chrome DevTools"]');+ await expect(dashboard.locator('.inspector-frame')).not.toBeVisible();+ await devToolsButton.click();+ await expect(dashboard.locator('.inspector-frame')).toBeVisible();+});++test('should pick locator from browser', async ({ cli, server, openDashboard }) => {+ server.setContent('/', '<button style="position:fixed;top:0;left:0;width:200px;height:100px">Submit</button>', 'text/html');++ await cli('open', server.PREFIX);++ const dashboard = await openDashboard();+ await dashboard.locator('.session-chip').click();++ const pickBtn = dashboard.locator('button.nav-btn[title="Pick locator"]');+ await pickBtn.click();++ await expect(dashboard.locator('div.dashboard-view')).toContainClass('interactive');++ // Intercept clipboard writes before clicking pick.+ const copyPromise = dashboard.evaluate(() => {+ if (!navigator.clipboard)+ return 'no clipboard';+ return new Promise<string>(f => {+ const original = navigator.clipboard.writeText;+ navigator.clipboard.writeText = text => {+ f(text);+ navigator.clipboard.writeText = original;+ return navigator.clipboard.writeText(text);+ };+ });+ }).catch(e => `Exception in eval: ${e}`);++ await expect(async () => {+ await dashboard.locator('img#display').click({ position: { x: 50, y: 25 } });+ const text = await Promise.race([+ copyPromise,+ new Promise<string>(f => setTimeout(() => f('timeout'), 1000))+ ]);+ expect(text).toContain('Submit');+ }).toPass();+});diff --git a/tests/mcp/http.spec.ts b/tests/mcp/http.spec.tsindex 1d54a60532..dae97466b2 100644--- a/tests/mcp/http.spec.ts+++ b/tests/mcp/http.spec.ts@@ -15,7 +15,6 @@*/import fs from 'fs';-import net from 'net';import dns from 'dns';import { ChildProcess, spawn } from 'child_process';@@ -360,7 +359,7 @@ test('should respect allowed hosts (negative)', async ({ serverEndpoint }) => {expect(await response.text()).toContain('Access is only allowed at example.com');});-test('should respect allowed hosts (positive)', async ({ serverEndpoint }) => {+test('should respect allowed hosts (positive)', async ({ serverEndpoint, findFreePort }) => {const port = await findFreePort();await serverEndpoint({args: [@@ -381,14 +380,3 @@ test('should be able to allow any host', async ({ serverEndpoint }) => {expect(response.status).toBe(400);expect(await response.text()).toBe('Invalid request');});--async function findFreePort(): Promise<number> {- return new Promise((resolve, reject) => {- const server = net.createServer();- server.listen(0, () => {- const { port } = server.address() as net.AddressInfo;- server.close(() => resolve(port));- });- server.on('error', reject);- });-}