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

Playwright报错:类型'APIRequest'不存在属性'get',求解决方案

问题:将Playwright API调用提取到独立模块后出现类型错误

我在test.spec.ts中的以下代码可以正常运行:

//@ts-check
import { test, request } from '@playwright/test'

test('api test - to see if Playwright API calls are working', async ({ request }) => {
  const response = await request.get(`https://catfact.ninja/fact`);
  const statusCode = response.status()
  const responseBody = JSON.parse(await response.text())
})

我想要将该API调用提取到独立模块中,于是在单独文件中编写了如下代码:

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

export async function getCatInfo() {
    const response = await request.get(`https://catfact.ninja/fact`)
}

但VS Code提示错误:Property 'get' does not exist on type 'APIRequest'

请问我哪里操作错误了?


解答

核心问题是你混淆了Playwright中两种不同的request对象:

  • 原测试代码里的{ request }是从测试上下文解构出的**APIRequestContext实例**,它自带get、post等请求方法,这也是原代码能正常运行的原因。
  • 而你在独立模块直接导入的request是**APIRequest类型的工具对象**,它的作用是创建请求上下文(比如调用request.newContext()),本身并没有get方法,所以会触发类型错误。

你可以用两种方式修正:

方式一:传递测试上下文的request实例到模块

修改独立模块代码:

// 示例文件名:catApi.ts
export async function getCatInfo(request) {
    const response = await request.get(`https://catfact.ninja/fact`);
    // 可提前处理响应,返回解析后的数据
    return await response.json();
}

在测试文件中调用:

//@ts-check
import { test } from '@playwright/test';
import { getCatInfo } from './catApi';

test('api test - to see if Playwright API calls are working', async ({ request }) => {
  const catFact = await getCatInfo(request);
  console.log(catFact.fact);
})

方式二:在模块内自行创建请求上下文

如果不想依赖测试上下文的request,可以在模块里单独创建并管理请求上下文:

// catApi.ts
import { request } from '@playwright/test';

export async function getCatInfo() {
    const requestContext = await request.newContext();
    const response = await requestContext.get(`https://catfact.ninja/fact`);
    const result = await response.json();
    await requestContext.dispose(); // 用完记得销毁上下文,避免资源泄漏
    return result;
}

这种方式无需从测试上下文传参,但要注意手动处理上下文的生命周期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 21:52:33