Promptles
Testing & Quality

Stub vs Spy

intermediate

Definition

Two test helpers, often confused. A stub replaces a real function with a fake one that always returns whatever the test wants: used to control what the code sees. A spy doesn't change anything; it lets the real function run and just quietly takes notes about how it was called: used to check that the right calls happened.

In the wild

Testing a 'show user profile' page. The test uses a stub to make the 'fetch user' function always return the same fake user, so the test isn't dependent on a real database. Separately, it uses a spy on the 'log analytics' function: the real one runs, but the spy keeps track of what it was told to log so the test can confirm a 'profile viewed' event was sent.

More from Testing & Quality