You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

0 Días
12 Hrs
33 Min
10 Seg
Curso de Cypress Avanzado

Curso de Cypress Avanzado

Javier Fuentes Mora

Javier Fuentes Mora

Interceptando Network Requests

8/29
Resources

How to make your tests more resilient with network request interception?

When we talk about automated tests, it is key that they are resilient to unexpected changes in third-party applications or libraries. Often, they fail due to bugs not so much in our code, but in those libraries or services we use. These services may be unstable or not allocate enough resources to us in test environments. This is where Cypress, a popular testing tool, provides us with effective options such as network request interception to improve the reliability of our tests.

What is a CI.request and how is it used?

For those who are already familiar with Cypress, the CI.request command allows you to make requests to APIs directly:

cy.request('https://pokeapi.co/api/v2/pokemon/ditto').then((response) => { expect(response.body).to.have.property('name', 'ditto'); expect(response.status).to.eq(200); });

This command is especially useful for authenticating users or simulating interactions with backend services. However, it does not allow us to validate how our interface handles these network requests.

How to intercept network requests in Cypress?

The intercept feature in Cypress covers this limitation. It allows capturing and modifying requests, as well as validating that certain queries are performed when interacting with the interface.

Practical example of interception

We can intercept a GET request to analyze how the application responds:

cy.intercept('GET', '**/pokemon/1').as('getBulbasaur');cy.visit('/some-page');cy.contains('Bulbasaur').should('be.visible');
cy.wait('@getBulbasaur').then((interception) => { expect(interception.response.body.name).to.eq('bulbasaur'); expect(interception.response.statusCode).to.eq(200);});
  1. Interception: We define a rule to intercept requests to a specific URL. In this case, the one for the Pokémon Bulbasaur.
  2. Visit and validation: We navigate to a page and check that "Bulbasaur" is visible.
  3. Wait for response: We use cy.wait to wait for the intercepted request to complete, allowing us to verify that the response is as expected.

Adaptation to slow environments.

What if an API is known to be slow? We can adjust the timeout to ensure that tests have enough time:

cy.wait('@getBulbasaur', { timeout: 20000 }).its('response.statusCode').should('eq', 200);

Using intercepts in automated testing with Cypress can be a valuable tool. Not only does it allow us to verify that you are collaborating correctly with APIs, but also to simulate certain conditions of the production environment without risk, validating how our applications behave in response to unexpected changes or temporary failures.

Remember that improving the resilience of your tests is essential to minimize failures and reduce maintenance. Continue to explore the broad capabilities that Cypress offers, and continue to hone your skills with each test.

Contributions 4

Questions 1

Sort by:

Want to see more contributions, questions and answers from the community?

Si la request dura mucho…

// Wait until a propertyPath answers a value...
cy.wait("@myApiResponse1").its("response.statusCode").should("eq", 200);

// Wait and use a timeout
cy.wait("@myApiResponse1", { timeout: 2000 });

mi codigo ```js describe("Interceptando network requests", ()=>{ it("Repaso de request", ()=>{ cy.request("https://pokeapi.co/api/v2/pokemon/ditto").then(response =>{ expect(response.body).to.have.property("name", "ditto"); expect(response.status).to.eq(200); cy.log(response.body); }); }); it('Prueba de intercept simple', ()=>{ cy.intercept("GET","https://pokeapi.co/api/v2/pokemon-species/1").as("bulbasaur"); cy.visit("/"); cy.contains("Bulbasaur").parent().parent().within( element=>{ cy.wrap(element).contains("Más detalles").click(); }); /*cy.wait("@bulbasaur").then((interception) =>{ cy.log(interception); expect(interception.response.body).to.have.property("name", "bulbasaur"); expect(interception.response.statusCode).to.eq(200); });*/ //cy.wait('@bulbasaur',{timeout: 2000}); cy.wait('@bulbasaur').its('response.statusCode').should('eq',200); }); }); ```describe("Interceptando network requests", ()=>{     it("Repaso de request", ()=>{        cy.request("https://pokeapi.co/api/v2/pokemon/ditto").then(response =>{            expect(response.body).to.have.property("name", "ditto");            expect(response.status).to.eq(200);            cy.log(response.body);        });    });     it('Prueba de intercept simple', ()=>{        cy.intercept("GET","https://pokeapi.co/api/v2/pokemon-species/1").as("bulbasaur");         cy.visit("/");         cy.contains("Bulbasaur").parent().parent().within( element=>{            cy.wrap(element).contains("Más detalles").click();        });                /\*cy.wait("@bulbasaur").then((interception) =>{            cy.log(interception);            expect(interception.response.body).to.have.property("name", "bulbasaur");            expect(interception.response.statusCode).to.eq(200);        });\*/                //cy.wait('@bulbasaur',{timeout: 2000});         cy.wait('@bulbasaur').its('response.statusCode').should('eq',200);    });});

Como no existen los archivos de la clase, hice este pequeno ejemplo que explica la clase de forma simple…


// Save my Interceptor into a alias
cy.intercept("GET", "https://my-api.com/1").as("myApiResponse1");
cy.visit("/my-page-list");

// Navigate into a detail Page
cy.get("#detailBtn-1").click();

// Use my alias 
cy.wait("@myApiResponse1").then((interception) => {
	cy.log(interception);
	// Assert my Interceptor
	expect(interception.body).to.have.property("property-name", "value");
});