Spies, Stubs, and Clocks

Learn what spies, stubs, and clocks are, and how they can control the behavior of our application.

First and foremost, why do we need to control some of the behaviors of our application? Wouldn’t we want to test it from a user’s perspective without modifying anything programmatically? There can be several reasons for controlling the original behavior of our app. Let’s take a look at some.


Reasons for controlling behavior

When we want to modify the behavior of our application, here are a couple of scenarios that will make our test suite more robust:

  • Avoid side effects, such as a bad network connection
  • We are dealing with Promises, and we want to automatically resolve or reject them.
  • We want to force things to fail to test a failure path.
  • We want to force things to pass to test a happy path.
  • We want to speed up the test suite by shortcutting redundant steps like logging in to test the application.

These are some of the reasons for modifying behavior, we will look at others shortly.

Now let’s take a look at some ways to help with the above-mentioned points.


Stubbing functions

The most common way to modify a function’s behavior is by using stubs. They are most commonly used in unit tests, but they can still be useful for some cases in integration or end-to-end testing. We can stub functions using the cy.stub command:

// Replace user.get() with a stubbed function
user.get = cy.stub();
cy.stub(user, 'get');

The two examples above are equivalent. We can also force functions to have a return value of our choice:

Get hands-on with 1200+ tech skills courses.