HTML and CSS Reference
In-Depth Information
We don't need to check if
data
exists because
urlParams
was designed to
handle a missing argument. Note that because the encoding interface was separated
from the ajax interface, it would probably be a good idea to add a feature test for it.
We could force such a feature test by writing a test that removed the method locally
for the duration of the test and assert that the method did not throw an exception.
I'll leave that as an exercise.
12.6.2.2 Sending Encoded Data
Next up is sending the data. For POST requests we want the data sent to
send
,as
Listing 12.60 specifies.
Listing 12.60
Expecting data to be sent for POST requests
"test should send data with send() for POST": function () {
var object = { field1: "
$
13", field2: "Lots of data!" };
var expected = tddjs.util.urlParams(object);
ajax.request("/url", { data: object, method: "POST" });
assertEquals(expected, this.xhr.send.args[0]);
}
This test fails because we are force-feeding the
send
method
null
. Also note
how we now trust
tddjs.util.urlParams
to provide the expected value. It
should have its own set of tests, which should guarantee as much. If we are reluctant
to trust it, we could stub it out to avoid it cluttering up the test. Some developers
always stub or mock out dependencies such as this, and theoretically, not doing so
makes the unit test slightly bend toward an integration test. We will discuss pros and
cons of different levels of stubbing and mocking more extensively in Chapter 16,
Mocking and Stubbing.
For now, we will leave
tddjs.util.urlParams
live in
our tests.
To make the test pass we need to add data handling to
ajax.request
,as
Listing 12.61 does.
Listing 12.61
Initial attempt at handling data
function request(url, options) {
/* ... */
options = tddjs.extend({}, options);
options.data = tddjs.util.urlParams(options.data);
var data = null;