是否有可能在 Cypress 中测试被阻止的网络请求?

use*_*975 7 request cypress cypress-intercept

我们的页面上有多个 API 请求。当调用失败时,某些行为是预期的。是否有可能如何在赛普拉斯中测试被阻止的网络请求?

Cra*_*yne 15

在您的规范文件中阻止

假设您想阻止对 Google 标签管理器的所有请求

你可以执行以下操作:

cy.intercept({
  method: 'GET',
  url: 'https://www.googletagmanager.com/*'
}, req => {
  req.destroy();
});

// navigate to the page that calls google tag manager
Run Code Online (Sandbox Code Playgroud)

与往常一样,在调用之前拦截该调用非常重要。

参考:https://docs.cypress.io/api/commands/intercept#Controlling-the-response


通过 Cypress 设置进行阻止

在 cypress.json 文件中添加以下内容:

{
  "blockHosts": [
    "www.googletagmanager.com"
  ]
}
Run Code Online (Sandbox Code Playgroud)

参考: https: //docs.cypress.io/guides/references/configuration#blockHosts