HTML and CSS Reference
In-Depth Information
16.6 Mocks
Mocks have been mentioned many times throughout the topic, but never explained
or used. The reason is that manually creating mocks is not as easy as manually creat-
ing stubs and spies. Like stubs, mocks are objects with pre-programmed behavior.
Additionally, a mock has pre-programmed expectations and built-in behavior ver-
ification. Using mocks turns the test upside-down; first we state the expectations,
then we exercise the system. Finally we verify that all the mock's expectations were
met. Listing 16.17 shows an example using with the “start polling” test.
Listing 16.17 Mocking ajax.poll
"test connect should start polling": function () {
this.client.url = "/my/url";
var mock = sinon.mock(ajax)
mock.expects("poll").withArgs("/my/url").returns({});
this.client.connect();
mock.verify();
}
This test states its success criteria upfront. It does so by creating a mock for the
ajax object, and adding an expectation on it. It expects the poll method to be
called exactly once, with the URL as argument. In contrast to the stubs we've used
so far, mocks fail early. If the poll method is called a second time, it immediately
throws an ExpectationError , failing the test.
16.6.1 Restoring Mocked Methods
The mocks can be undone just like the stubs, by calling restore on the mocked
method. Additionally, calling verify implicitly restores the mocked method. How-
ever, if the test throws an exception before the call to verify , we might end up
leaking the mock into another test, causing a ripple effect.
Sinon's sandbox feature can mitigate the problem for mocks just as much
as it does for stubs. When wrapping the test method in a sinon.test call,
it will receive a mock method as its second parameter, suitable for safe mock-
ing. After the test finishes, Sinon not only restores all stubs and mocks, it also
conveniently verifies all mocks, meaning that the above test could be written like
Listing 16.18.
 
 
Search WWH ::




Custom Search