HTML and CSS Reference
In-Depth Information
12.4.2 Stubbing the XMLHttpRequest Object
In order for the get method to do anything at all, it needs to create an XML-
HttpRequest object. We simply expect it to create one using ajax.create .
Note that this does introduce a somewhat tight coupling between the request API
and the create API. A better idea would probably be to inject the transport object.
However, we will keep things simple for now. Later when we see the big picture
clearer, we can always refactor to improve.
In order to verify that an object is created, or rather, that a method is called,
we need to somehow fake the original implementation. Stubbing and mocking are
two ways to create objects that mimic real objects in tests. Along with fakes and
dummies , they are often collectively referred to as test doubles . Manual Stubbing
Test doubles are usually introduced in tests either when original implementations are
awkward to use or when we need to isolate an interface from its dependencies. In the
case of XMLHttpRequest , we want to avoid the real thing for both reasons. Rather
than creating an actual object, Listing 12.15 is going to stub out the ajax.create
method, make a call to ajax.get , and then assert that ajax.create was called.
Listing 12.15 Manually stubbing the create method
"test should obtain an XMLHttpRequest object": function () {
var originalCreate = ajax.create;
ajax.create = function () {
ajax.create.called = true;
ajax.create = originalCreate;
The test stores a reference to the original method and overwrites it with a func-
tion that, when called, sets a flag that the test can assert on. Finally, the original
method is restored. There are a couple of problems with this solution. First of all, if
this test fails, the original method will not be restored. Asserts throw an Assert-
Error exception when they fail, meaning that the last line won't be executed unless
Search WWH ::

Custom Search