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

使用 Playwright Workspace 配置视觉比较

本文介绍如何在使用 Playwright Workspaces 时正确配置 Playwright 的视觉比较测试。 可能会出现意外的测试失败,因为 Playwright 的快照在本地浏览器和远程浏览器之间有所不同。

背景

Playwright 测试运行程序使用主机 OS 作为预期屏幕截图路径的一部分。 如果在不同于主机的 OS 上使用远程浏览器运行测试,则视觉对象比较测试会失败。 建议仅在使用服务时运行视觉对象比较。 如果在服务上截取屏幕截图,无需将它们与本地设置比较,因为它们并不匹配。

配置 ignoreSnapshots

使用 Playwright Workspaces 时,可以使用此选项ignoreSnapshots仅运行视觉比较。

  1. 在不使用服务的原始 ignoreSnapshots: true 中设置 playwright.config.ts
  2. ignoreSnapshots: false 中设置 playwright.service.config.ts

使用服务时,其配置将替代 playwright.config.ts,并运行视觉对象比较。

配置快照路径

若要为特定项目或整个配置配置配置快照路径,可以设置 snapshotPathTemplate 选项

// This path is exactly like the default path, but replaces OS with hardcoded value that is used on the service (linux).
config.snapshotPathTemplate = '{snapshotDir}/{testFileDir}/{testFileName}-snapshots/{arg}{-projectName}-linux{ext}'

// This is an alternative path where you keep screenshots in a separate directory, one per service OS (linux in this case).
config.snapshotPathTemplate = '{testDir}/__screenshots__/{testFilePath}/linux/{arg}{ext}';

服务配置示例

运行视觉对象比较并配置 snapshotPathTemplate 路径的服务配置示例:

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

/* Learn more about service configuration at https://aka.ms/pww/docs/config */
export default defineConfig(
  config,
  createAzurePlaywrightConfig(config, {
    exposeNetwork: '<loopback>',
    connectTimeout: 30000,
    os: ServiceOS.LINUX,
    credential: new DefaultAzureCredential()
  }),
  {
    ignoreSnapshots: false,
    // Enable screenshot testing and configure directory with expectations. 
    snapshotPathTemplate: `{testDir}/__screenshots__/{testFilePath}/${ServiceOS.LINUX}/{arg}{ext}`,
  }
);