Creating Test Doubles

Learn how to create test doubles and the methods for creating doubles.

Doubles creation

The testdouble.js library has three methods for creating doubles, which are analogous to RSpec’s double method. Which one we use largely depends on whether our JavaScript code is primarily structured around functions, objects, or classes.

Function replacement

We can use the td.function method if we’re trying to replace a bare function. If we call it with no arguments, the result is a bare function suitable for passing as a dependency to code under test.

Object replacement

We may want to replace an entire object or class instance more frequently. To replace an object, use the td.object function. There are two ways to use td.object. If we don’t have a real object, but we know the interface of the object we want, we can call td.object with an array of strings, representing properties of the object that are functions. We then get a test-double object where each of those strings is a test double-fake function, like this:

Get hands-on with 1200+ tech skills courses.