ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

Playwright Test 配置文件深度解析:读懂 playwright.config 的每一项配置及其底层实现

Playwright Test 配置文件深度解析:读懂 playwright.config 的每一项配置及其底层实现 Playwright Test 配置文件深度解析读懂 playwright.config 的每一项配置及其底层实现【免费下载链接】playwrightPlaywright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.项目地址: https://gitcode.com/GitHub_Trending/pl/playwrightPlaywright 测试的运行行为几乎完全由playwright.config.ts配置文件驱动测试文件的查找范围、并行度、重试策略、报告器、断言超时、全局设置脚本以及 web 服务器启动方式都在这里定义。本文基于仓库中的配置文档 test-configuration-js.md 与测试运行器源码 config.ts、configLoader.ts逐一讲解每个配置项的语义、默认值与生效时机帮助你写出可复制、可在 CI 中稳定运行的配置并理解配置在 Playwright 内部的加载、校验与合并流程。配置文件的定位、加载与校验在展开具体选项之前先弄清楚 Playwright 是如何找到并加载配置文件的。从源码 configLoader.ts 的resolveConfigFile可以看到未通过--config指定文件时Playwright 在当前工作目录中依次尝试playwright.config.ts、.js、.mts、.mjs、.cts、.cjs这六种扩展名传入目录时在该目录内做同样的查找找不到配置文件则把该目录本身当作测试根目录加载到的模块支持export default导出loadUserConfig会自动解包default属性见 configLoader.ts#L95-L100。配置文件导出后首先经过validateConfig的类型校验configLoader.ts#L128-L256例如forbidOnly必须是布尔值、globalTimeout必须是非负数字、globalSetup/globalTeardown可以是字符串或字符串数组、shard.total必须为正整数且shard.current不能超过total、updateSnapshots只接受all/changed/missing/none之一等。配置写错会在启动阶段立刻报出带文件名的错误而不是在测试运行中静默失效。官方推荐的defineConfig来自 configLoader.ts#L31-L87。从源码实现看它并非简单的类型提示函数而是支持合并多份配置对象顶层字段后写覆盖先写expect、use两个对象逐键浅合并webServer自动归一为数组projects则按name做逐项目合并。这意味着“基础配置 CI 覆盖配置”可以写成defineConfig(base, ciOverrides)的形式这正是多环境配置的常用做法。文档还特别强调了一个容易踩的坑测试运行器选项test runner options必须放在顶层不要放进use段落。use中的选项属于浏览器上下文/测试夹具选项会被合并进 project 的运行时选项而testDir、retries、workers等只作用于运行器本身放错位置不会报错但也不会生效。从 config.ts#L169-L200 的FullProjectInternal构造逻辑可以看到运行器字段timeout、retries、testDir等从顶层 config 与 project 按优先级取值而use则是把 config 层、project 层与 CLI 覆盖层做mergeObjects合并。基础配置最常用选项的完整示例下面是文档给出的基础配置示例也是绝大多数项目playwright.config.ts的骨架import { defineConfig, devices } from playwright/test; export default defineConfig({ // Look for test files in the tests directory, relative to this configuration file. testDir: tests, // Run all tests in parallel. fullyParallel: true, // Fail the build on CI if you accidentally left test.only in the source code. forbidOnly: !!process.env.CI, // Retry on CI only. retries: process.env.CI ? 2 : 0, // Opt out of parallel tests on CI. workers: process.env.CI ? 1 : undefined, // Limit the whole test run, so that it fails with a report instead of hanging. globalTimeout: 60 * 60 * 1000, // Reporter to use reporter: html, use: { // Base URL to use in actions like await page.goto(/). baseURL: http://localhost:3000, // Collect trace when retrying the failed test. trace: on-first-retry, }, // Configure projects for major browsers. projects: [ { name: chromium, use: { ...devices[Desktop Chrome] }, }, ], // Run your local dev server before starting the tests. webServer: { command: npm run start, url: http://localhost:3000, reuseExistingServer: !process.env.CI, }, });各选项的含义及源码依据如下| 选项 | 说明 | 默认值源码依据 | | :- | :- | :- | |testDir| 测试文件所在目录相对配置文件解析同时也是rootDirconfig.ts#L89 | 配置文件所在目录 | |fullyParallel| 让所有文件中的所有测试并行调度而不是文件内串行 |falseconfig.ts#L92详见 Parallelism 与 Sharding | |forbidOnly| 源码中残留test.only时以错误退出适合 CI |falseconfig.ts#L91 | |retries| 每个测试的最大重试次数可被 project 覆盖 |0config.ts#L187详见 Test Retries | |workers| 并发 worker 进程数上限也可写50%这类百分比 |50%即逻辑 CPU 核心数的 50%config.ts#L110 | |globalTimeout| 整个测试运行的总时限到时停止运行但报告器仍会产出报告 |0不限制--debug时强制为 0config.ts#L95详见 Timeouts | |reporter| 使用的报告器可写字符串或[name, arg]元组数组 | CI 下dot本地listconfig.ts#L307 | |projects| 在多种配置/多个浏览器上运行测试 | 未定义时整个 config 视为单 project | |use| 传给测试夹具的选项baseURL、trace等按 config 层 → project 层 → CLI 覆盖层合并 | — | |webServer| 测试运行前启动的本地服务器 |null|其中workers的解析值得单独说明。config.ts 的resolveWorkers支持两种写法正整数或以%结尾的百分比百分比模式按os.cpus().length * percent / 100向下取整且保证至少为 1。另外注意debug/pause模式下 workers 会被强制置为 1config.ts#L110、config.ts#L208-L209调试时不会出现多进程干扰。reporter的内置取值在 config.ts#L292 有明确列表list、line、dot、json、junit、null、github、html、blob、perfetto非内置报告器会按 Node 模块路径解析允许传入自定义报告器包。更多报告器细节见 Test Reporters。测试文件过滤testMatch 与 testIgnore用 glob 模式或正则表达式控制哪些文件参与运行import { defineConfig } from playwright/test; export default defineConfig({ // Glob patterns or regular expressions to ignore test files. testIgnore: *test-assets, // Glob patterns or regular expressions that match test files. testMatch: *todo-tests/*.spec.ts, });| 选项 | 说明 | | :- | :- | |testIgnore| 查找测试文件时应忽略的 glob 模式或正则例如*test-assets| |testMatch| 匹配测试文件的 glob 模式或正则例如*todo-tests/*.spec.ts|从源码看这两个选项的实际默认值比文档表述更宽config.ts#L193 中testMatch的默认模式是**/*.(spec|test).?(c|m)[jt]s?(x)即同时覆盖.js、.ts、.mjs、.cjs等 ESM/CJS 扩展名的*.spec.*与*.test.*文件testIgnore默认为空数组config.ts#L192。两者都支持字符串、正则、数组三种形式且可定义在顶层 config 或单个 project 上取值遵循“project 优先于 config”的规则见 config.ts#L192-L193 的takeFirst顺序。进阶配置产物目录、全局脚本与单测超时文档给出的进阶配置示例import { defineConfig } from playwright/test; export default defineConfig({ // Folder for test artifacts such as screenshots, videos, traces, etc. outputDir: test-results, // path to the global setup files. globalSetup: require.resolve(./global-setup), // path to the global teardown files. globalTeardown: require.resolve(./global-teardown), // Each test is given 30 seconds. timeout: 30000, });| 选项 | 说明 | 源码依据 | | :- | :- | :- | |globalSetup| 全局设置文件路径require/加载后在所有测试之前执行须导出单个函数可以是字符串数组按顺序执行多个脚本 |resolveScript先按 configDir 相对路径解析本地文件失败则回退到 Node 模块解析config.ts#L297-L304脚本收集逻辑见 config.ts#L73 | |globalTeardown| 全局收尾文件路径在所有测试之后执行须导出单个函数 | 同上config.ts#L74 | |outputDir| 截图、视频、trace 等测试产物目录 | 默认位于package.json所在目录下的test-resultsconfig.ts#L183也可被 CLI--output覆盖 | |timeout| 每个测试的超时时间默认 30 秒测试函数、测试夹具与beforeEach钩子的耗时都计入该超时 |defaultTimeout 30000定义于 config.ts#L40取值顺序为 CLI project config 默认值config.ts#L194详见 Timeouts |需要说明两点实现细节globalSetup/globalTeardown允许数组形式configLoader.ts#L139-L159 的校验逻辑明确支持数组逐项校验字符串适合“数据库初始化 → 上传测试数据”这类多阶段准备timeout是 project 级选项可以整体设置也可以只在某个 project 上设置实现不同模块不同的超时预算。--debuginspector模式下超时会强制归零config.ts#L194方便单步调试。Expect 断言选项独立的超时与快照比较参数expect段配置断言库的行为与测试级timeout相互独立import { defineConfig } from playwright/test; export default defineConfig({ expect: { // Maximum time expect() should wait for the condition to be met. timeout: 5000, toHaveScreenshot: { // An acceptable amount of pixels that could be different, unset by default. maxDiffPixels: 10, }, toMatchSnapshot: { // An acceptable ratio of pixels that are different to the // total amount of pixels, between 0 and 1. maxDiffPixelRatio: 0.1, }, }, });| 选项 | 说明 | 源码依据 | | :- | :- | :- | |expect| Web-first 断言如expect(locator).toHaveText()默认有独立的 5 秒等待超时 | 默认值defaultExpectTimeout 5000定义在 expect.ts#L173匹配器调用时的取值链是单次调用传参 expect 配置 默认值expect.ts#L392 | |toHaveScreenshot|expect(locator).toHaveScreenshot()的参数配置maxDiffPixels为允许的最大像素差数默认未设置 | 配置经expectConfig().toHaveScreenshot传入SnapshotHelpertoMatchSnapshot.ts#L344-L349 | |toMatchSnapshot|expect(locator).toMatchSnapshot()的参数配置maxDiffPixelRatio为允许的差异像素占总像素比例0 到 1 之间 | 同样经expectConfig().toMatchSnapshot生效toMatchSnapshot.ts#L272-L278 |expect段的合并规则与use类似project 级expect优先于顶层 config 的expectconfig.ts#L201 的takeFirst(projectConfig.expect, config.expect, {})因此可以在某个 project 里单独放宽或收紧断言超时。更细致的测试与 expect 超时体系见 Timeouts断言本身见 Assertions。webServer随测试启动本地开发服务器基础配置中的webServer用于在测试开始前拉起被测的本地服务器。从插件实现 webServerPlugin.ts 可以看到其工作机制启动command指定的进程后轮询url是否可达可达才进入测试运行reuseExistingServer: true时若目标 URL 已可访问则直接复用现有服务器若为false且端口已被占用则会抛出类似 “is already used, make sure that nothing is running on the port/url or set reuseExistingServer:true in config.webServer” 的错误webServerPlugin.ts#L97-L103文档示例中reuseExistingServer: !process.env.CI正是惯用组合本地开发时复用已在跑的 dev server 省时间CI 上强制全新启动以保证环境干净。另外从 config.ts#L120-L130 可以看到webServer还支持数组形式同时启动多个服务器如前端 后端两个进程此时内部统一按数组处理。配置优先级总览综合 config.ts 中takeFirst的取值顺序各类选项的优先级可以概括为CLI 覆盖--workers、--retries、--timeout、--reporter等命令行参数project 级配置projects[i]中同名字段顶层 config 配置内置默认值timeout: 30000、workers: 50%、globalTimeout: 0、retries: 0、forbidOnly: false、updateSnapshots: missing、reportSlowTests: { max: 5, threshold: 300000 }等均定义在 config.ts#L86-L112 与 config.ts#L40。use选项则是 config 层、project 层、CLI 覆盖层三者做对象合并config.ts#L174后合并者覆盖前者。掌握这套优先级后配合defineConfig的多配置合并能力就能用同一份仓库配置同时满足本地开发、CI 与多浏览器矩阵的运行需求。小结playwright.config.ts是 Playwright 测试的“单一事实来源”文件查找规则testDir/testMatch/testIgnore、调度参数fullyParallel/workers、健壮性参数forbidOnly/retries/globalTimeout、产物目录outputDir、全局脚本globalSetup/globalTeardown、断言行为expect与服务器编排webServer全部在此声明所有配置在加载期即完成类型校验配置错误会尽早暴露运行时遵循“CLI project config 默认值”的优先级use与expect走对象合并想继续深入可按主题阅读仓库文档并行与分片、分片、超时体系、报告器、重试、断言或对照源码 config.ts 与 configLoader.ts 逐行验证每个选项的默认值与合并顺序。【免费下载链接】playwrightPlaywright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.项目地址: https://gitcode.com/GitHub_Trending/pl/playwright创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表