HTML and CSS Reference
In-Depth Information
12.4.2.3 Improved Stubbing
To kill the manual stub open method, Listing 12.22 improves the stubFn func-
tion by having it record the arguments it receives and making them available for
verification in tests.
Listing 12.22 Improving the stub helper
function stubFn(returnValue) {
var fn = function () {
fn.called = true;
fn.args = arguments;
return returnValue;
};
fn.called = false;
return fn;
}
Using the improved stubFn cleans up the second test considerably, as seen in
Listing 12.23.
Listing 12.23 Using the improved stub function
"test should call open with method, url, async flag":
function () {
var openStub = stubFn();
ajax.create = stubFn({ open: openStub });
var url = "/url";
ajax.get(url);
assertEquals(["GET", url, true], openStub.args);
}
We now generate a stub for ajax.create that is instructed to return an
object with one property: a stubbed open method. To verify the test we assert that
open was called with the correct arguments.
The second problem was that adding the call to transport.open caused the
first test, which didn't return an object from the stubbed ajax.create method, to
fail. To fix this we will extract a fake XMLHttpRequest object, which can be shared
between tests by stubbing ajax.create to return it. The stub can be conveniently
created in the test case's setUp . We will start with the fakeXMLHttpRequest
object, which can be seen in Listing 12.24. Save it in lib/fake _ xhr.js .
 
Search WWH ::




Custom Search