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

cy.intercept未匹配目标URL,误拦截其他请求的问题排查

解决Cypress cy.intercept匹配错误的问题

你的问题核心是cy.intercept默认的字符串URL匹配是包含匹配,而非精确匹配,所以https://api.example.com/test/foo会匹配所有包含该片段的请求,包括/test/foo/bar。

修正方案

以下两种方法可以实现精确匹配:

1. 使用正则表达式精确匹配

将URL参数替换为正则表达式,通过^(开头)和$(结尾)限定完全匹配:

before(() => {
  cy.intercept('POST', /^https:\/\/api\.example\.com\/test\/foo$/).as('foo');
});

2. 使用RouteMatcher对象精确匹配

通过配置RouteMatcher对象,明确指定hostname和pathname的精确值:

before(() => {
  cy.intercept('POST', {
    hostname: 'api.example.com',
    pathname: '/test/foo'
  }).as('foo');
});

额外注意事项

  • 检查代码中的URL拼写:你提供的代码里写的是https://api.example/com/test/foo,这里example/com应为example.com(缺少一个点),虽然你说拦截到了错误请求,但这个拼写错误可能导致后续问题,建议修正。
  • form-data类型的请求不会影响cy.intercept的匹配规则,请求顺序也不是问题,核心还是匹配逻辑的设置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 10:45:38