Specifying Test Double Behavior
Explore how to define behaviors for JavaScript test doubles with testdouble.js, including stubbing methods, handling arguments with matchers, and managing asynchronous calls with promises to improve unit testing effectiveness.
We'll cover the following...
Once we have a testdouble.js function, we need to specify some behavior, analogous to how RSpec’s test doubles use allow and expect with chained methods like to_receive.
Adding behavior
In testdouble.js, we add behavior with the when method, and the API to it is a little unusual. Here’s a basic usage:
const fake = td.object["remoteInit"]
td.when(fake.remoteInit(1)).thenReturn(7)
There are two parts to this when invocation:
- The call to
whenitself. - The chained method afterward that defines the behavior.
The argument to when is meant to be the entire call to the test double, potentially with arguments specified. The call demonstrates that the test expects to be made by the code under test.
In this case, we expect the test to make the call fake.remoteInit(1) to cause the test double to return the value 7. If we make the call fake.remoteInit(2), changing the argument, the specified behavior is not triggered, ...