HTML and CSS Reference
In-Depth Information
16.5.3 Built-in Behavior Verification
Sinon comes with a few assertions that can be used for clearer behavior verification.
The problem with the assert in Listing 16.12 is that the resulting error message in
case of test failure will be “expected true but was false,” which isn't very helpful. By
using Sinon's asserts, the error message will instead look something like “expected
poll to be called once but was called 0 times.” Listing 16.14 shows the test updated
to use assertCalledWith .
Listing 16.14 Using tailored asserts for behavior verification
"test connect should start polling": function () {
this.client.url = "/my/url";
stub(ajax, "poll").returns({});
sinon.assert.calledWith(ajax.poll, "/my/url");
Sinon is a stand alone library, and does not require JsTestDriver. The reason this
works “out of the box” with JsTestDriver is that Sinon uses the same definition of
failure, which is throwing an AssertError . To use the asserts with another testing
framework, simply set the type of exception to throw on failure by overriding the
sinon.failException string. If your testing framework of choice does not fail
by throwing an exception, override the method to do the right thing.
To sugar things up even more, Sinon can inject its assertions into another object,
allowing them to live side-by-side with the testing framework's assertions. JsTest-
Driver uses global assertions. Listing 16.15 shows the necessary code for completely
seamless integration.
Listing 16.15 Mixing Sinon's assertions with the default JsTestDriver ones
// Typically done in a global helper to share among
// test cases
sinon.assert.expose(this, true, false);
TestCase("CometClientConnectTest", {
/* ... */
"test connect should start polling": sinon.test(function (
stub) {
this.client.url = "/my/url";
stub(ajax, "poll").returns({});
Search WWH ::

Custom Search