We have multiple API requests on our page. When a call fails, certain behavior is expected. Is there a possibility of how to test a blocked network request in Cypress?
-
https://docs.cypress.io/api/commands/route.html#Options – Aleksey L. Sep 02 '20 at 12:15
-
@AlekseyL. cy.intercept() is the successor to cy.route() as of Cypress 6.0.0. – Benny Meade Nov 15 '21 at 10:39
4 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

- 4,499
- 4
- 35
- 50
To test certain behavior of the application when the API call fails, use an intercept command with failOnStatusCode: false
. The default value is true
but this will not allow the test to proceed further.
A simple example:
it('tests the API call failed', () => {
cy.intercept({
method: 'GET',
url: 'api/resource/1',
failOnStatusCode: false
}).as('api')
cy.visit('/')
cy.wait('@api')
cy.get('#error-massage').should('be.visible')
})

- 23
- 6
There are two more ways to block a cypress test call
To force a network error by adding
{ forceNetworkError: true }
.Example
cy.intercept('https://my-website.com/specific-path.html', { forceNetworkError: true })
.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 -

- 466
- 2
- 15
If you would like to block Sleeknote popup which was blocking accessibility to UI components in our case, You can use below code to block network requests.
cy.intercept(
{
url: 'https://sleeknotestaticcontent.sleeknote.com/**',
middleware: true,
},
(req) => {
req.destroy();
}
)

- 2,416
- 2
- 20
- 16