Background Image
Table of Contents Table of Contents
Previous Page  297 / 478 Next Page
Information
Show Menu
Previous Page 297 / 478 Next Page
Page Background

Aside on Ajax

If you’ve never used Ajax before, here is a very brief overview. You may find it useful to

read up on it elsewhere before proceeding though.

Ajax stands for “Asynchronous JavaScript and XML”, although the XML part is a bit of

a misnomer these days, since everyone usually sends text or JSON rather than XML. It’s

a way of letting your client-side JavaScript code send and receive information via the

HTTP protocol (GET and POST requests), but do so “asynchronously”, ie, without

blocking and without needing to reload the page.

Here we’re going to use Ajax requests to send a POST request to our login view, sending

it the assertion information from the Persona UI. We’ll use the

jQuery Ajax convenience functions

.

Let’s add this “module” after the first test, before the test for

"initialize calls navi

gator.id.watch"

:

accounts/static/tests/tests.html (ch15l045).

var user, token, urls, mockNavigator, requests, xhr; //

module("navigator.id.watch tests", {

setup: function () {

user = 'current user'; //

token = 'csrf token';

urls = { login: 'login url', logout: 'logout url' };

mockNavigator = {

id: {

watch: sinon.mock()

}

};

xhr = sinon.useFakeXMLHttpRequest(); //

requests = []; //

xhr.onCreate = function (request) { requests.push(request); }; //

},

teardown: function () {

mockNavigator.id.watch.reset(); //

xhr.restore(); //

}

});

test("initialize calls navigator.id.watch", function () {

[...]

We pull out the variables

user

,

token

,

urls

, etc. up to a higher scope, so that

they’ll be available to all of the tests in the file.

We initialise said variables inside the

setup

function, which, just like a

uni

ttest

setUp

function, will run before each test. That includes our

mockNaviga

tor

.

JavaScript Unit Tests Involving External Components: Our First Mocks!

|

269