Spies, Stubs and Mocks

Idan Mor (sidanmor)
sidanmor
Published in
2 min readJan 16, 2017

--

Ever wondered what the different between spies, stubs and mocks? In this blog, I will try to explain it to you.

What is a test spy?

A test spy is a function that records arguments, return value, the value of this and exception thrown (if any) for all its calls. A test spy can be an anonymous function or it can wrap an existing function.

Test spies are useful to test both callbacks and how certain functions/methods are used throughout the system under test.

What are stubs?

Test stubs are functions (spies) with pre-programmed behavior. They support the full test spy API in addition to methods which can be used to alter the stub’s behavior.

As spies, stubs can be either anonymous, or wrap existing functions. When wrapping an existing function with a stub, the original function is not called.

Use a stub when you want to control a method’s behavior from a test to force the code down a specific path or when you want to prevent a specific method from being called directly.

What are mocks?

Mocks (and mock expectations) are fake methods (like spies) with pre-programmed behavior (like stubs) as well as pre-programmed expectations. A mock will fail your test if it is not used as expected.

Mocks should only be used for the method under test. In every unit test, there should be one unit under test. If you want to control how your unit is being used and like stating expectations upfront (as opposed to asserting after the fact), use a mock.

Mocks come with built-in expectations that may fail your test. Thus, they enforce implementation details. The rule of thumb is: if you wouldn’t add an assertion for some specific call, don’t mock it. Use a stub instead. In general you should never have more than one mock (possibly with several expectations) in a single test.

References:

--

--

Full-Stack Team Leader, Senior Full-Stack Software Engineer and Javascript Ninja