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

使用Playwright+TypeScript报错:APIRequestContext无newContext属性

解决Playwright中Property 'newContext' does not exist on type 'APIRequestContext'报错

问题原因

你调用newContext的request变量是已创建的APIRequestContext实例,这个实例仅用于发送HTTP请求(如get/post等),并不具备创建新上下文的newContext方法。newContext是属于APIRequest类的方法,也就是Playwright提供的顶层请求对象(比如测试用例中的request fixture)。

修正方案

场景1:在Playwright测试用例中使用(推荐)

直接使用测试用例提供的request fixture(这是APIRequest实例)来创建新上下文:

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

test('带令牌的API上下文示例', async ({ request }) => {
  const accessToken = '你的令牌内容';
  
  // 这里的request是APIRequest实例,支持newContext方法
  const apiContext = await request.newContext({
    extraHTTPHeaders: {
      Authorization: `Bearer ${accessToken}`,
      'Content-Type': 'application/json',
    },
  });

  // 使用新上下文发送请求
  const response = await apiContext.get('/api/目标接口');
  // ...后续业务逻辑
});

场景2:手动创建API请求对象(非测试场景)

如果是在测试外的场景使用,需要手动实例化APIRequest:

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

async function createAuthApiContext() {
  const request = new APIRequest();
  const accessToken = '你的令牌内容';
  
  const apiContext = await request.newContext({
    extraHTTPHeaders: {
      Authorization: `Bearer ${accessToken}`,
      'Content-Type': 'application/json',
    },
  });

  return apiContext;
}

额外注意

如果你的代码中之前已经有一个名为request的APIRequestContext变量,建议重命名避免混淆,比如改为existingApiContext,防止和顶层的APIRequest对象冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 01:32:37