HTML and CSS Reference
In-Depth Information
16.6.3 Multiple Expectations
Using mocks, we can form complex expectations by expecting several calls, some
or all with differing arguments and
this
values. The expectation returned by
expects
can be tuned by calling methods such as
withArgs
as seen above;
withExactArgs
, which does not allow excessive arguments; as well as
never
,
once
,
twice
, and the more generic
atLeast
,
atMost
, and
exactly
methods,
which tune the number of expected calls.
Listing 16.20 shows one of the original Comet client tests, which expects the
connect
method not to be called once the client is connected.
Listing 16.20
Expecting
connect
not to be called a second time
"test should not connect if connected": function () {
this.client.url = "/my/url";
ajax.poll = stubFn({});
this.client.connect();
ajax.poll = stubFn({});
this.client.connect();
assertFalse(ajax.poll.called);
}
Using Sinon mocks, we can rewrite this test in two ways. The default expectation
on mocks is that they will be called one time, and one time only. Never calling
them, or calling them two times causes an
ExpectationError
, failing the test.
Even though one call is the default expectation, we can make it explicit, as seen in
Listing 16.21.
Listing 16.21
Explicitly expecting one call
"test should not connect if connected":
sinon.test(function (stub, mock) {
this.client.url = "/my/url";
mock(ajax).expects("poll").once().returns({});
this.client.connect();
this.client.connect();
})
Notice how the
this
value retains its implicit binding to the test case, even as
a callback to
sinon.test
. The second way to write this test using mocks, which
mirrors the original test more closely, can be seen in Listing 16.22.