newcasio
newcasio

Reputation: 253

Understanding Cypress cy.route

I have written assertions with cy.route previously with success. However, writing a new test to test the successful (200) response of GET and POST requests have got myself doubting my understanding. I have repeatedly read the related docs and watched the relevant cypress video but my new test still does not run as expected.

My code uses the following pattern

cy.server();      
cy.route({method:'POST', url: '/api/**'}).as('call');    

//click the button that triggers the request .   
cy.get('#button').click(); 
cy.wait('@call').then((xhr)=>
    {
        //assert returned status code ===200
    }

);

My current understanding is cy.route acts like an event listener, but in this case listening for a POST request to a matching URL.

When the button is clicked that sends the request, the request is sent as per normal, but the cy.route is alerted and awaits (cy.wait) the response.

Am I correct in my understanding? Does the order of the where the click occurs matter? That is, I cannot send the request then setup the listener?

Upvotes: 2

Views: 5950

Answers (1)

Akshay Vijay Jain
Akshay Vijay Jain

Reputation: 15945

  1. Yes, cy.route is kind of listener for xhr requests
  2. Yes, order matters, first we need to define the listener and then the xhr request should happen. i.e. cy.route does not track the xhr calls happened before it's definition

Upvotes: 1

Related Questions