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

Playwright API测试:如何拦截内部fetch请求并做断言?

如何在Playwright API测试中拦截服务器端发起的HTTP请求

由于Playwright的API测试是直接向你的服务器发送HTTP请求,服务器内部发起的fetch属于Node.js环境中的请求,无法通过浏览器测试里的page.route拦截。你可以通过以下两种方式实现拦截和断言:

方法一:使用nock库拦截特定域名请求

nock是Node.js环境下专门用于拦截HTTP请求的工具,可精准匹配目标URL并验证调用情况。

  1. 安装依赖:
npm install nock --save-dev
  1. 编写测试代码:
import { test, expect } from '@playwright/test';
import nock from 'nock';

test('验证占位符API被服务器调用', async ({ request }) => {
  // 拦截jsonplaceholder的GET请求
  const mockInterceptor = nock('https://jsonplaceholder.typicode.com')
    .get('/todos/1')
    .reply(200, { id: 1, title: '模拟数据' });

  // 调用你的目标API路由
  const apiResponse = await request.get('/your-target-route');
  expect(apiResponse.status()).toBe(405);

  // 断言请求确实被发起(拦截器捕获到了请求)
  expect(mockInterceptor.isDone()).toBe(true);
});

方法二:Mock Node.js全局的fetch函数

直接替换Node.js的global.fetch,记录调用状态并返回模拟响应:

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

test('验证服务器端fetch被调用', async ({ request }) => {
  let fetchInvoked = false;
  const originalFetch = global.fetch;

  // 替换全局fetch
  global.fetch = async (url) => {
    if (url === 'https://jsonplaceholder.typicode.com/todos/1') {
      fetchInvoked = true;
      // 返回符合fetch规范的模拟响应
      return {
        json: async () => ({ id: 1, title: '模拟Todo' }),
        ok: true
      };
    }
    // 其他请求走原始fetch
    return originalFetch(url);
  };

  try {
    // 调用你的API路由
    const apiResponse = await request.get('/your-target-route');
    expect(apiResponse.status()).toBe(405);
    // 断言fetch被调用
    expect(fetchInvoked).toBe(true);
  } finally {
    // 测试结束后恢复原始fetch,避免影响其他测试
    global.fetch = originalFetch;
  }
});

关键说明

  • page.route仅能拦截浏览器页面上下文发起的请求,而API测试中服务器内部的请求属于Node.js进程,不受其控制。
  • 两种方法都能避免实际发起外部请求,同时验证服务器是否正确触发了目标API调用。

内容的提问来源于stack exchange,提问作者J. Hesters

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 21:51:16