Stubbing Responses in end-to-end tests?



  • So i've been trying out Cypress for the past few days, and im liking the tool so far. One feature it enables is being able to stub network requests (I think only xhr right now). Im sure other tools allow this, but im a bit confused at "when" I should be using this option.

    For example lets say I have a Add Widget form. It has a Title, Description and Type fields (All being text inputs and Type being a dropdown).

    Typically I would write tests to probably verify the inputs worked (Although some would say that's really testing the "browser" and not behavior). And then testing maybe a failed submission (not having required fields) and then a successful submission (That sends a xhr request to the JSON API in the backend).

    Now I suppose I could stub the response from the server...which would probably be a 200 status code (or whatever failed status code for failure) but that isn't really actually confirming that adding the Widget actually even works.

    Cypress in it's documentation suggests to have one test that's happy path and goes through the actual testing path as a user would, and then to stub the rest. However im not actually sure when/where I would be stubbing responses in an end-to-end test in a typical Front-End + JSON API backend setup.

    When exactly would I use this? Maybe for login? But in the actual case im setting an auth token (Since it's using JWT) in localstorage to avoid needing the user to actually login. But that's not really actually stubbing either.



  • Cypress stub() and spy() are adopted from Sinon.js spies and stubs. Based on Sinon documentation:

    When to use stubs?

    Use a stub when you want to:

    Control a method’s behavior from a test to force the code down a specific path. Examples >include forcing a method to throw an error in order to test error handling.

    When you want to prevent a specific method from being called directly (possibly because >it triggers undesired behavior, such as a XMLHttpRequest or similar).

    So basically you may want to "stub" anything that redirects you somewhere, as cypress can't switch tabs, or cover some rainy day scenarios (i.e. inform the user that email already exists in the database, without creating the actual test data behind it).



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2