Home > Software design >  Can Cypress intercept requests being made directly to a server?
Can Cypress intercept requests being made directly to a server?

Time:12-28

I have been trying to intercept a server request using Cypress' intercept method. I have noticed that Cypress can intercept requests made through the front-end/browser, however, the intercept method doesn't work if I make a request directly to the back-end server.

Let me clarify what I mean:

  • One thing is intercepting a request that the front-end/browser makes to the back-end server.
  • Another thing is intercepting a call that doesn't use the browser but calls directly the back-end endpoint.

For example: I can create a user using the front-end interface or I can create a user calling the back-end endpoint directly (directly calling the server).

Coming back to my question. Is there a way to intercept a call that was made directly to the back-end endpoint?

This is what I have tried so far:

  • I wrote a regex to intercept api/v0/customers
  • I then made a request to http://locahost:5440/api/v0/customers (which is the URL of the server)
  • Finally, I waited for the request to happen

Timeout request using Cypress intercept method

    cy.intercept(/^\/api\/v0\/customers\/$/).as('createCustomer');
    cy.request(createCustomer(customerData, headers));
    cy.wait('@createCustomer').then(({ status, body }) => {
      const customerId = body.customer_id;
      console.log(body);
      expect(status).equal(201);
    });

Here's the problem: There was a timeout error.

  • As you can see in the image, I'm making a request to http://locahost:5440 which is the server URL. NOTE: I made sure the server was up and running.
  • The regex is also correct and it will match the endpoint http://locahost:5440/api/v0/customers

I suspect that intercept only works for requests being made through the browser. Is this assertion correct? I couldn't find this answer anywhere in the Cypress docs. Is there a way for me to intercept a call being made directly to a server (not using the browser)?

CodePudding user response:

You don't have to intercept the requests you explicitly make with cypress, just use .then to get the response, like this:

cy.request(createCustomer(customerData, headers)).then((response) => { 
    const customerId = response.body.customer_id; 
    console.log(response.body);
    expect(response.status).equal(201);
});

Reference: https://docs.cypress.io/api/commands/request#Yields

  • Related