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

如何在Playwright中创建API请求新Context?Cucumber集成测试报错求助

解决Cucumber集成Playwright API测试的异步冲突错误及Context创建方法

一、异步冲突错误原因与修复

报错Error: function uses multiple asynchronous interfaces: callback and promise是因为Cucumber函数同时混用了回调和Promise两种异步模式,按以下步骤解决:

  1. 统一异步写法:所有钩子(Before/After)和步骤函数都使用async/await(Promise模式),绝对不要在函数参数里添加回调参数。
  2. 弃用全局变量传参:不要用global传递Playwright实例,改用Cucumber的World对象共享上下文,这是官方推荐的规范方式。

二、正确创建Playwright API请求Context

API测试不需要创建page,仅需创建request context即可,以下是完整配置流程:

1. 自定义Cucumber World(新建world.js)

const { setWorldConstructor } = require('@cucumber/cucumber');
const { chromium } = require('playwright');

class CustomWorld {
  constructor() {
    this.browser = null;
    this.requestContext = null;
  }

  async init() {
    // 启动无头浏览器(API测试无需可视化界面)
    this.browser = await chromium.launch({ headless: true });
    // 创建API请求专用Context,可配置全局请求头、基础URL
    this.requestContext = await this.browser.newContext({
      baseURL: 'https://apistaging.swordfish-new-co-ecs-nonprod.com',
      extraHTTPHeaders: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Api-Version': '2'
      }
    });
  }

  async destroy() {
    // 测试结束后清理资源
    await this.requestContext.dispose();
    await this.browser.close();
  }
}

setWorldConstructor(CustomWorld);

2. 配置钩子(新建hooks.js)

const { Before, After } = require('@cucumber/cucumber');

Before(async function () {
  await this.init();
});

After(async function () {
  await this.destroy();
});

3. 修正Step逻辑(修改Step.js)

去掉全局变量,改用World对象获取request上下文,同时修复冗余的await写法:

const { Given, Then } = require('@cucumber/cucumber');
const { expect } = require('@playwright/test');

Given('I send a request for authentication token', async function () {
  // 替换为实际测试用的令牌
  const token = '你的测试令牌';
  
  // 用request context发起请求,参数用params更规范
  const response = await this.requestContext.get('/ned/employers', {
    params: {
      $top: '2',
      name: 'Nike'
    },
    headers: {
      'Authorization': `Bearer ${token}`
    }
  });

  // 修复双重await的错误写法
  const responseBody = await response.json();
  await expect(responseBody).toHaveLength(2);
  console.log(responseBody);
});

Then('I get an access token', async function () {
  // 这里添加令牌验证逻辑,示例:
  // await expect(responseBody.access_token).toBeDefined();
});

4. 额外排查点

如果仍触发异步错误,检查:

  • 所有步骤、钩子函数都未添加回调参数(比如不要写成Before(async (callback) => { ... callback() }))
  • 确保@cucumber/cucumber和playwright使用最新稳定兼容版本

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 06:20:33