'Is there a possibility to block network requests in Cypress?

we have multiple API requests on our page. When a call fails, certain behavior is expected. Is there a possibility of how to block a network request in Cypress?



Solution 1:[1]

Blocking in your spec file

Say you wanted to block all requests to google tag manager

you could do the following:

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

// navigate to the page that calls google tag manager

As always, it's important to intercept the call BEFORE it is made.

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


Blocking via Cypress settings

in your cypress.json file add the following:

{
  "blockHosts": [
    "www.googletagmanager.com"
  ]
}

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1