HTML and CSS Reference
In-Depth Information
16.5.1 Creating a Stub Function
Creating a stub function using Sinon is very similar to our trusty old stubFn .
Listing 16.9 shows a test from the observable test case, updated to use sinon.
stub .
Listing 16.9 Using Sinon to create simple function stubs
"test should call all observers": function () {
var observable = Object.create(tddjs.util.observable);
var observer1 = sinon.stub();
var observer2 = sinon.stub();
observable.addObserver(observer1);
observable.addObserver(observer2);
observable.notifyObservers();
assertTrue(observer1.called);
assertTrue(observer2.called);
}
The only noticeable difference in this example is the way the stubs are created.
Rather than the original inline function that set a property on the function itself, we
now have a simple call to sinon.stub .
16.5.2 Stubbing a Method
Throwaway stubs are simple enough to create inline, and don't necessarily warrant
the use of an external library. Stubbing global methods, however, is a bit more
hassle because we must make sure to restore the original method after running the
test. Listing 16.10 shows an extract of the setUp and tearDown methods of the
Comet client test case along with a test using the stubFn method on the global
ajax.poll .
Listing 16.10 Spying manually
TestCase("CometClientConnectTest", {
setUp: function () {
this.client = Object.create(ajax.cometClient);
this.ajaxPoll = ajax.poll;
},
tearDown: function () {
ajax.poll = this.ajaxPoll;
},
 
Search WWH ::




Custom Search