Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Assert on XHR Requests in Cypress


    In this lesson, we'll learn to test the seam between frontend and backend -- our XHR requests. Using cy.route as if we were mocking our backend requests, we can instead spy on the request, and intercept its data to run tests against.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    Instructor: In this lesson, let's learn how to assert on XHR request. It starts with the cy.server. Typically, when we've used this in the past, it's because we were going to mark our backend request. In this case, we're not marking any request, but we do have to start the cy.server in order to use cy.route which will allow us to spy on and assert on the XHR request.

    Also, when we view cy.route in the past, it's been because we are returning response, but in this case, we're just not going to specify response. It's going to still hit the backend as it normally would.

    We will use an alias as we normally do. This will be our create to-do request. We need to get our new to-do input. We'll type into it first to-do, and we'll press enter.

    We'll do cy.wait, we'll wait for that create to-do request which will hit the real backend. Then we'll receive our XHR response, and we can make assertions on it here. Let's press debug so we can take a look at what that looks like.

    Here we see it. XHR is our subject. We see that there is a request object, which has a body and its headers, and the response object which has body and headers. What we can do here, we can say cy.wrap XHR.response.body, and then we can chain that as we normally would. We can say it should inaudible equal and then we'll give it one text.

    First to-do completed. False, that kind of thing, we can do the same thing for our request if we're interested or we could do it for our status code and say that the status should equal 201, which will be our created code. We can make both of those assertions and rerun this.

    That's it. That's how you assert on the XHR request.