Using testdouble.js

Learn about the test-double library, partial doubles in the testdouble.js file, and how to use the testdouble.js file.

The testdouble.js test-double library

The testdouble.js is a test-double library written by Justin Searls and his crew at a company called Test Double. The library is very strict about the kinds of test doubles; it helps us create a specific pattern of testing and program design. Searls explains that in the documentation.

Partial doubles in testdouble.js

For our purposes, the most significant part of the testdouble.js API compared to RSpec’s mock package is that testdouble.js makes it difficult to impossible to stub only one or two methods of an existing object. That means it’s hard to create a partial test double. In testdouble.js, the idea is that it is generally safer and clearer to replace an entire object with a test double rather than have an object exist as part test double, part real object. We can’t argue with the theory, though if we’re used to RSpec’s looser test double style, working with testdouble.js requires some adjustment. As we’ll see, the resulting code’s design is, to some extent, determined by drawing a boundary around the logic that is easy to stub together. This is by design because the test is being used to determine the logical structure of the code.

Using testdouble.js

Using testdouble.js happens in the following three steps:

  • We declare the double.
  • We define its behavior with the td.when method.
  • We optionally verify its usage after the test has run with the td.verify.

Note: Please note that this is not a complete guide to testdouble.js. We can access the very complete documentation online here.

Get hands-on with 1200+ tech skills courses.