Is there a possibility to block network requests in Cypress?

Viewed 3577

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?

2 Answers

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

There are two more ways to block a cypress test call

  1. To force a network error by adding { forceNetworkError: true }.

    Example cy.intercept('https://my-website.com/specific-path.html', { forceNetworkError: true }).

  2. By adding body block with status code error of 404 and delay.

cy.intercept(
  {
    method: 'GET',
    pathname: '/todos'
  },
  {
    body: 'test does not allow it',
    statusCode: 404,
    delayMs: 2000
  }
)

source links -

  1. https://github.com/cypress-io/cypress/issues/3820#issuecomment-1136238501.
  2. https://glebbahmutov.com/blog/cypress-intercept-problems/#simulate-network-error
Related