Assert on XHR Requests in Cypress

Brett Cassette
InstructorBrett Cassette
Share this video with your friends

Social Share Links

Send Tweet
Published 6 years ago
Updated 4 years ago

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.

Instructor: [00:00] 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.

[00:26] 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.

[00:38] 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.

[00:55] 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.

[01:15] 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.

[01:50] 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.

[02:23] That's it. That's how you assert on the XHR request.