同一Cypress Spec文件中拦截两个接口的正则使用求助
解决Cypress拦截API时路径匹配冲突的问题
问题原因
你遇到的问题是因为Cypress的cy.intercept使用字符串路径时默认做前缀匹配:/client/users会匹配所有以它开头的请求,包括/client/users/ip_user,导致请求被错误的拦截规则捕获,响应内容混淆。
解决方案:用正则表达式精确匹配端点
通过正则的^(开头)和$(结尾)约束,确保每个拦截规则只匹配精确的目标路径,避免前缀匹配的干扰。
修正后的代码
// 精确匹配 /client/users 端点,仅匹配该路径本身 cy.intercept('GET', /^\/client\/users$/, { fixture: 'users.json' }).as('user') // 精确匹配 /client/users/ip_user 端点 cy.intercept('GET', /^\/client\/users\/ip_user$/, { fixture: 'ipuser.json' }).as('ipuser') cy.wait('@ipuser').then((interception) => { interception.response.body.data.attributes.limit = 10000 interception.response.body.data.attributes.amount = 10000 cy.log(JSON.stringify(interception.response.body)) cy.writeFile(filename, JSON.stringify(interception.response.body)) })
关键说明
^\/client\/users$:正则表示请求路径必须完全等于/client/users,不会匹配任何以它为前缀的子路径。- 移除代码中重复定义的
cy.intercept('GET', '/client/users/ip_user', ...),重复定义会覆盖之前的拦截规则,引发不必要的问题。 - 正则匹配不受定义顺序影响,每个规则只会命中自己的精确路径。
内容的提问来源于stack exchange,提问作者140218-M
相关产品推荐
相关产品推荐

