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

如何在Playwright中复刻Cypress的cy.intercept功能?

从Cypress迁移到Playwright:处理动态URL的API请求等待

问题场景

将测试套件从Cypress迁移至Playwright时,需要等待包含动态值的API请求返回200响应后再执行后续操作。此前在Cypress中用*作为通配符匹配动态URL,现在需要找到Playwright中的替代方案。

原Cypress代码:

cy.intercept('GET',`${apiUrl}/employee/*/information`).as('GETemployeeInformation');

尝试的Playwright代码(无法正确匹配):

async isSignedIn() {
    await this.page.waitForResponse(response => response.url().includes("/employee/*/information") && response.status() === 200);
}

解决方案

你当前代码的问题在于includes方法里的*是作为普通字符串来匹配的,Playwright不会将其识别为通配符。正确的做法是使用正则表达式来匹配包含动态部分的URL:

方案1:直接用正则匹配

如果动态部分是数字(比如员工ID),可以用\d+匹配:

async isSignedIn() {
  await this.page.waitForResponse(response => 
    /\/employee\/\d+\/information/.test(response.url()) && response.status() === 200
  );
}

如果动态部分可以是任意非斜杠字符,用[^/]+匹配:

async isSignedIn() {
  await this.page.waitForResponse(response => 
    /\/employee\/[^/]+\/information/.test(response.url()) && response.status() === 200
  );
}

方案2:结合API地址拼接正则

如果需要复用apiUrl变量,可以动态生成正则表达式(注意转义URL中的特殊字符):

const apiUrl = '你的API基础地址';
const targetUrlRegex = new RegExp(`${apiUrl.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}/employee/[^/]+/information`);

async isSignedIn() {
  await this.page.waitForResponse(response => 
    targetUrlRegex.test(response.url()) && response.status() === 200
  );
}

说明

Playwright的waitForResponse方法接受一个断言函数,通过正则表达式匹配URL,完全可以替代Cypress中*通配符的作用,精准匹配带有动态参数的API请求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 10:16:12