You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PlaywrightTestConfig中添加自定义配置项deleteAPIcall?

解决Playwright添加自定义配置项的类型报错问题

下面提供三种可行方案,按需选择:

方案一:扩展Playwright的配置类型(推荐)

通过TypeScript的模块扩展机制,给PlaywrightTestConfig接口添加自定义字段,从根源解决类型报错,同时保留完整的类型提示。

修改你的playwright.config.ts代码如下:

import { PlaywrightTestConfig } from '@playwright/test';

// 扩展Playwright配置类型
declare module '@playwright/test' {
  interface PlaywrightTestConfig {
    deleteAPIcall?: string; // 自定义字段,可选类型可根据实际需求调整
  }
}

const config: PlaywrightTestConfig = {
  testMatch: 'tests/*.ts',
  outputDir: 'tests/test-results',
  retries: 1,
  reporter: [['html', { open: 'never', outputFolder: '/test-results/html' }]],
  globalSetup: require.resolve('./tests/global-setup'),
  deleteAPIcall: 'https://delAPICall.company.com', // 现在不会触发类型报错
  use: {
    headless: true,
    screenshot: 'only-on-failure',
    trace: 'retain-on-failure',
    baseURL: 'http://localhost:3000',
    storageState: 'storageState.json'
  },
  timeout: 60000,
};

export default config;

方案二:使用类型断言快速绕过检查

如果不想扩展全局类型,直接用类型断言把配置对象指定为PlaywrightTestConfig与自定义字段的联合类型,适合临时调试或快速验证场景:

import { PlaywrightTestConfig } from '@playwright/test';

const config = {
  testMatch: 'tests/*.ts',
  outputDir: 'tests/test-results',
  retries: 1,
  reporter: [['html', { open: 'never', outputFolder: '/test-results/html' }]],
  globalSetup: require.resolve('./tests/global-setup'),
  deleteAPIcall: 'https://delAPICall.company.com',
  use: {
    headless: true,
    screenshot: 'only-on-failure',
    trace: 'retain-on-failure',
    baseURL: 'http://localhost:3000',
    storageState: 'storageState.json'
  },
  timeout: 60000,
} as PlaywrightTestConfig & { deleteAPIcall: string };

export default config;

方案三:将自定义配置放到use字段中

Playwright的use配置本身支持扩展自定义属性,无需修改全局类型,适合把配置和测试上下文绑定的场景:

import { PlaywrightTestConfig } from '@playwright/test';

const config: PlaywrightTestConfig = {
  testMatch: 'tests/*.ts',
  outputDir: 'tests/test-results',
  retries: 1,
  reporter: [['html', { open: 'never', outputFolder: '/test-results/html' }]],
  globalSetup: require.resolve('./tests/global-setup'),
  use: {
    headless: true,
    screenshot: 'only-on-failure',
    trace: 'retain-on-failure',
    baseURL: 'http://localhost:3000',
    storageState: 'storageState.json',
    deleteAPIcall: 'https://delAPICall.company.com' // 把自定义配置放到use字段内
  },
  timeout: 60000,
};

export default config;

之后在测试代码中获取该配置:

import { test } from '@playwright/test';

test('示例测试', async ({ page }) => {
  const deleteAPI = test.info().config.use.deleteAPIcall as string;
  // 使用deleteAPI执行后续操作
});

内容的提问来源于stack exchange,提问作者Panface

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 00:45:37