DEV Community

Cover image for Cypress Network Interceptors in 20 Minutes
John Peters
John Peters

Posted on • Updated on

Cypress Network Interceptors in 20 Minutes

Image: Cypress Trees and Black Swan : Fine Art America

it("should be able to intercept the request and response to Person", () => {
      cy.server();  
      setInterceptor(/Person/)  
         .visit(`${homepage}/eligibility`)  
         .wait("@Route")  
         .should(function (xhr) {            
            expect(xhr.status).to.eq(200);
            expect(xhr.requestHeaders).to.have.property("Accept");
            expect(xhr.method).to.eq("GET");
            expect(xhr.response.body).length.greaterThan(2);
         });
   });

function setInterceptor(regex) {
   cy.route({
      method: "GET",
      url: regex,
      onRequest: (req) => {},
      onResponse: (rsp) => {
         debugger;
      },
   }).as("Route");
   return cy;
}
Enter fullscreen mode Exit fullscreen mode

In the lines above, the cy.server() call is required by Cypress to intercept requests and responses. Next we are calling setInterceptor(regex), with a Regex expression to parse the URL. The cy.Route() takes in an object defining when to intercept, and has two callbacks (onRequest, onResponse). The debugger statement allows for a breakpoint on the response. So far the key requirements are the cy.server() and cy.route() calls.

cy.server();  
      setInterceptor(/Person/)  
         .visit(`${homepage}/eligibility`)  
         .wait("@Route")  
Enter fullscreen mode Exit fullscreen mode

We next; .visit the page that will call the Person endpoint. Finally we wait for the @route to complete. Note this is an arbitrary name we used inside setInterceptor using this syntax .as("Route").

The XMLHttpRequest, response

We opened the browser within Cypress (showing the page we were testing), Pressed F12 and started the test. The debugger statement in the setInterceptor routine provided us this view on the response.

Alt Text

Pretty cool way to test endpoints but,all being driven from your web site! This is the main reason Cypress is better than Karma.

Take Away

Cypress gives us function far superior to Karma, Protractor, and Selenium in that we can actually interrupt network requests and responses. I've heard that we can change headers too. I like Cypress!

JWP2020

Top comments (0)