Test XHR Failure Conditions with Cypress

Andy Van Slaars
InstructorAndy Van Slaars
Share this video with your friends

Social Share Links

Send Tweet
Published 6 years ago
Updated 5 years ago

Testing your application’s behavior when an XHR call results in an error can be difficult. The use of stubs for XHR calls makes it easy for us to setup failure scenarios and ensure that our front-end responds the way we expect. In this lesson, we’ll stub a 500 response for a form submission and verify that our application responds appropriately.

Instructor: [00:00] Here I've created a new test with the description "Shows an error message for a failed form submission." One of the advantages of stubbing out our network request in these integration tests is that it's very easy for us to set up a failure situation that would be difficult to set up otherwise.

[00:17] We'll start by defining a constant that's going to hold the string we'll type into our form. Then we'll call cy.server so we can stub out our API call. Then we'll call cy.route, passing it an options object.

[00:36] We're going to stub out our post request and we're going to respond with a failure.

[00:41] Our method here is going to be post. Our URL is going to be /api/todos. Then we're going to set a status of 500 and a response of an empty object.

[00:59] We're going to tag an "as" on here. We'll give this a name so that we can wait for it. With that set up, we'll call cy.seedAndVisit.

[01:09] Now we'll use cy.get to get our input. We'll issue the type command to type our new to-do into the input.

[01:27] We'll chain on a second type command to press the enter key. Upon enter, we want to wait for the response from our server, so we'll cy.wait using the @ symbol to prefix our alias. Then we'll use cy.get to get our list and select all of the LIs.

[01:53] We'll assert that it should have the length that it started with, of four. We're also going to cy.get another element that has the class error. This is the error message that we display when things go poorly in our application.

[02:14] Then we're just going to assert that this should be visible. With our test set up, I'll save that. I'll switch over to the Cypress UI.

[02:25] I'll run the form submission spec. We'll see that everything passes and our stubbed 500 response leads to our error message being displayed. Our item is not added to the list.

Pavel Klochkov
Pavel Klochkov
~ 5 years ago

Hi, at transcript in block with timing 02:14 you have the misprint on line 6 url: '/api/todos;, instead of url: '/api/todos',

Markdown supported.
Become a member to join the discussionEnroll Today