Wait for XHR Responses in a Cypress Test

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

Social Share Links

Send Tweet
Published 7 years ago
Updated 6 years ago

When testing interactions that require asynchronous calls, we’ll need to wait on responses to make sure we’re asserting about the application state at the right time. With Cypress, we don’t have to use arbitrary time periods to wait. In this lesson, we’ll see how to use an alias for a network request and wait for it to complete without having to wait longer than required or guess at the duration.

Instructor: [00:00] Here we have a test that stubs out a get call to our api/todos endpoint, responding with data from our fixture. Then it visits our page, and asserts that our list should have a length of four. If we run this test, we'll see that everything runs and passes as we expect.

[00:14] If I come back into the code, however, and I add an artificial delay using a setTimeout to my load call...We'll delay this by five seconds. We'll move that into the setTimeout, save it, we'll come back, and we'll rerun our test.

[00:39] We'll see that we get our visit, and Cypress tries for four seconds to retry that assertion. Then eventually, our call does get made and returned. We'll see that the output in our preview pane contains our items, but our test failed, because our items weren't there by the timeout that Cypress was using.

[00:56] It would be better if we could tell Cypress to wait for this API call before making our assertion. Back in our spec code, we're going to chain a call to the Cypress as command, and we're going to give it the name load.

[01:09] This is going to create an alias for our route. Then after our visit, we're going to call cy.wait, and we're going to pass it our load alias, prefixed with the @ symbol. With this in place, let's save our test, and we'll watch it run again.

[01:30] This time, we're still going to get the delay, but you'll see it's hanging on the wait. It's waiting for that load API call to be made. As soon as it is, it continues on with our test and runs our assertions. Now, our test is going to be more resilient to delays, whether artificial or intended.

[01:48] Our test code is going to more clearly communicate exactly what should happen. We're going to visit, we're going to wait for that load call to complete, and then we expect our list to have a length of four.

Ben
Ben
~ 6 years ago

at 0:49 Just to confirm -- it is NOT testing the XHR request to the real API, it is just delaying the stubbed request interception of that call?

Andy Van Slaars
Andy Van Slaarsinstructor
~ 6 years ago

Correct, but that wait behavior will work in an e2e test where there is a real delay in server response.

Markdown supported.
Become a member to join the discussionEnroll Today