Find Unstubbed Cypress Requests with Force 404

Brett Cassette
InstructorBrett Cassette
Share this video with your friends

Social Share Links

Send Tweet
Published 6 years ago
Updated 4 years ago

Requests that aren't stubbed will hit our real backend. To ensure we've stubbed all our routes, we can use the force404 method to send 404s from any unstubbed routes.

Instructor: [0:00] By default, cy.server will pass all requests to your back end. Now, that's a great configuration when we want to do full end-to-end testing, but oftentimes, we'll want to mock our back end to ensure that we get known data for our tests. How do we make sure we stub out every request our application makes?

[0:21] If we pass the option force 404 to cy.server, Cypress will ensure that any route that isn't stubbed returns a 404, breaking our app. Let's go ahead and pass it. We'll comment out our preload call.

[0:36] When Cypress tries to preload our todos, it returns a 404, which breaks our tests because the test expects two todos to be visible on the page. This is a great way to identify stubs that we haven't yet configured. To see this in action, let's comment these back in and move on to creating a test where we edit one of our todos.

[0:59] When we edit a todo, we double-click on the text field, change the text, and press enter. In order to replicate this, let's hit our selector playground, find the selector we need to target, and copy it to the clipboard. Let's append the selector to our test and double-click it.

[1:20] In our application, when we double-click on a todo, a new input appears on the page. That input is called todo input edit. If we want to clear the text in it, we can call clear. Then we can type updated todo, then the special key, enter.

[1:42] Back in Cypress, we see that we targeted the label. We doubled-clicked it, which caused the new input edit to appear on the page. We targeted that, cleared it, then typed updated todo enter.

[1:55] Finally, we see we have a 404 to the request api/todos/1, which is the update endpoint. The 404 alerts us that we haven't yet stubbed out our endpoint. Let's stub it out.

[2:08] This will be a cy.route. It'll be a put request to the api/todos/1 endpoint. We'll reply OK, and we'll alias it as update.

[2:23] Now all we need to do is cy.wait for @update. If we return to our test, we'll see that we no longer have a 404, but a 200 for the update. I find it's helpful to configure cy.server with force 404 anytime we aren't directly interacting with our back end.