你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

通过 Playwright 工作区使用云托管浏览器进行本地部署或专用托管的应用

了解如何使用 Playwright Workspaces 为本地部署的应用程序运行端到端测试。 Playwright Workspaces 使用云托管的远程浏览器大规模运行 Playwright 测试。 可以使用该服务针对 localhost 上的应用或基础结构上托管的应用运行测试。

Playwright 使你可以向远程浏览器公开客户端计算机上可用的网络。 在公开网络时,可以从 Playwright 测试代码连接到本地资源,而无需配置其他防火墙设置。

配置 Playwright 以公开本地网络

若要向远程浏览器公开本地网络和资源,可以在 Playwright 中使用 exposeNetwork 选项。 在 Playwright 文档中详细了解 exposeNetwork 选项

可以使用规则列表指定一个或多个网络。 例如,若要公开测试/暂存部署和 localhost*.test.internal-domain,*.staging.internal-domain,<loopback>

可以在 exposeNetwork 中配置 playwright.service.config.ts选项。 以下示例演示了如何使用 localhost 规则公开 <loopback> 网络。 还可以将 localhost 替换为要为服务启用的域。

import { createAzurePlaywrightConfig, ServiceOS } from "@azure/playwright";
import { defineConfig } from "@playwright/test";
import { DefaultAzureCredential } from "@azure/identity";
import config from "./playwright.config";

export default defineConfig(
  config,
  createAzurePlaywrightConfig(config, {
    exposeNetwork: '<loopback>', // Allow service to access the localhost.
    credential: new DefaultAzureCredential()
  }),
);

现在可以在 Playwright 测试代码中引用 localhost ,并使用 Playwright Workspaces 在云托管的浏览器上运行测试:

npx playwright test --config=playwright.service.config.ts --workers=20

可以在安装文件中配置 ExposeNetwork 该选项。 以下示例演示了如何使用 localhost 规则公开 <loopback> 网络。 还可以将 localhost 替换为要为服务启用的域。

using Azure.Developer.Playwright.NUnit;
using Azure.Developer.Playwright;
using Azure.Identity;
using System.Runtime.InteropServices;
using System;

namespace PlaywrightService.SampleTests; // Remember to change this as per your project namespace

[SetUpFixture]
public class PlaywrightServiceNUnitSetup : PlaywrightServiceBrowserNUnit
{
    public PlaywrightServiceNUnitSetup() : base(
        credential: new DefaultAzureCredential(),
        options: new PlaywrightServiceBrowserClientOptions()
        {
            ExposeNetwork = "<loopback>"
        }
    )
    {
        // no-op
    }
}

现在可以在 Playwright 测试代码中引用 localhost ,并使用 Playwright Workspaces 在云托管的浏览器上运行测试:

dotnet test -- NUnit.NumberOfTestWorkers=20