As long as the code we're testing remains relatively simple, Mocha and Expect.js are all that we need to test it. However, the code rarely remains simple, and there are two complications in particular that can make us need another tool, known as a mocking
library, to let us create fake versions or mocks of our objects.
First, let's imagine we want to test the following method of an imaginary ExampleModel
class:
foo: function() { this.bar += 1; this.baz(); }
Now, we'll want to test whether our foo
method calls the baz
method. However, at the same time, we will (presumably) already have a separate test of the baz
method itself. This leaves us with a dilemma: how can we test that foo
calls baz
without repeating the test code for baz
inside the test code for foo
?
Alternatively, let's consider another imaginary method that we might want to test:
fetchThenDoFoo: function() { this.fetch().done(this.foo); }
In this case, we want to test whether foo
is called after the fetch...