在 Microsoft Edge 中使用 Playwright 自动执行和测试

Playwright 库通过单个 API 提供跨浏览器自动化。

Playwright 是一个 Node.js库,用于通过单个 API 自动Chromium、FirefoxWebKit。 Playwright 旨在实现常青、强大、可靠且快速的跨浏览器 Web 自动化。 由于 Microsoft Edge 基于开源Chromium Web 平台构建,因此 Playwright 还能够自动Microsoft Edge。

默认情况下,Playwright 会启动 无外设浏览器 。 无外设浏览器不显示 UI,因此必须使用命令行。 还可以将 Playwright 配置为运行全 (非无外设) Microsoft Edge。

安装 Playwright 和浏览器

注意

Playwright 需要 Node.js 版本 12 或更高版本。 从命令行运行 node -v ,确保具有兼容版本的 Node.js。 Chromium、Firefox 和 WebKit 的浏览器二进制文件跨 Windows、macOS 和 Linux 工作。 有关详细信息,请参阅 Playwright 系统要求

首先,安装 Playwright 测试 以测试网站或应用:

npm i -D @playwright/test

若要安装浏览器,请运行以下命令,以下载ChromiumFirefoxWebKit

npx playwright install 

运行基本测试

Playwright 使用的方法对于其他浏览器测试框架(如 WebDriverPuppeteer)的用户会很熟悉。 可以创建浏览器实例,在浏览器中打开页面,然后使用 Playwright API作页面。

Playwright 测试是 Playwright 的测试运行程序,它为你启动浏览器和上下文。 然后,独立页面将传递到每个测试中,如以下基本测试所示:

// tests/foo.spec.ts
import { test, expect } from '@playwright/test';

test('basic test', async ({ page }) => {
  await page.goto('https://playwright.dev/');
  const title = page.locator('.navbar__inner .navbar__title');
  await expect(title).toHaveText('Playwright');
});

现在运行测试,如下所示:

npx playwright test

有关运行测试的详细信息,请参阅 Playwright > 入门

在 Microsoft Edge 中运行测试

若要在 Microsoft Edge 中运行测试,需要为 Playwright 测试创建配置文件,例如 playwright.config.ts。 在配置文件中,使用 Microsoft Edge 创建一个项目。

// playwright.config.ts
import { PlaywrightTestConfig } from '@playwright/test';

const config: PlaywrightTestConfig = {
  projects: [
    {
      name: 'Microsoft Edge',
      use: {
        // Supported Microsoft Edge channels are: msedge, msedge-beta, msedge-dev, msedge-canary
        channel: 'msedge',
      },
    },
  ],
};

export default config

如果系统上尚未安装 Microsoft Edge,请通过 Playwright 进行安装,如下所示:

npx playwright install msedge

使用上述 playwright.config.ts 文件时,Playwright Test 使用 Microsoft Edge 运行测试,如下所示:

npx playwright test --headed

使用 Playwright 作为库

还可以使用 Playwright 作为库,如以下代码所示。 此方法允许使用不同的测试运行程序。

// example.js
const playwright = require('playwright');

(async () => {
  const browser = await playwright.chromium.launch({
    channel: 'msedge',
  });
  const context = await browser.newContext();
  const page = await context.newPage();
  await page.goto('https://www.microsoft.com/edge');
  await page.screenshot({ path: 'example.png' });

  await browser.close();
})();

example.js生成的 example.png 文件

example.js 是 Playwright 启用的自动化和测试方案的简单演示。 若要在其他 Web 浏览器中获取屏幕截图,请将上述代码从 await playwright.chromium.launch 更改为以下代码:

Firefox:

  const browser = await playwright.firefox.launch({

WebKit:

  const browser = await playwright.webkit.launch({

有关 Playwright 和 Playwright 测试的详细信息,请转到 Playwright 网站。 查看 GitHub 上的 Playwright 存储库 。 若要与 Playwright 共享有关自动执行和测试网站或应用的反馈, 请提出问题

另请参阅