Search⌘ K
AI Features

Creating Test Doubles

Explore how to create effective test doubles in JavaScript using the testdouble.js library. Understand function, object, and ES6 class replacements to improve unit tests, ensuring that your tests reflect real code changes and handle dependencies efficiently.

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 ...