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

We also invoke Sinon’s

useFakeXMLHttpRequest

, which patches out the

browser’s Ajax capabilities.

There’s one more bit of boilerplate: we tell Sinon to take any Ajax requests and

put them into the

requests

array, so that we can inspect them in our tests.

Finally we have the cleanup—we “reset” the mock for the

watch

function in

between each test (otherwise calls from one test would show up in others).

And we put the JavaScript

XMLHttpRequest

back to the way we found it.

That lets us rewrite our two tests to be much shorter:

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

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

Superlists.Accounts.initialize(mockNavigator, user, token, urls);

equal(mockNavigator.id.watch.calledOnce, true, 'check watch function called');

});

test("watch sees current user", function () {

Superlists.Accounts.initialize(mockNavigator, user, token, urls);

var watchCallArgs = mockNavigator.id.watch.firstCall.args[0];

equal(watchCallArgs.loggedInUser, user, 'check user');

});

And they still pass, but their name is neatly prefixed with our module name:

4 assertions of 4 passed, 0 failed.

1. initialize binds sign in button to navigator.id.request (0, 2, 2)

2. navigator.id.watch tests: initialize calls navigator.id.watch (0, 1, 1)

3. navigator.id.watch tests: watch sees current user (0, 1, 1)

And here’s how we test the

onlogin

callback:

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

test("onlogin does ajax post to login url", function () {

Superlists.Accounts.initialize(mockNavigator, user, token, urls);

var onloginCallback = mockNavigator.id.watch.firstCall.args[0].onlogin; //

onloginCallback(); //

equal(requests.length, 1, 'check ajax request'); //

equal(requests[0].method, 'POST');

equal(requests[0].url, urls.login, 'check url');

});

test("onlogin sends assertion with csrf token", function () {

Superlists.Accounts.initialize(mockNavigator, user, token, urls);

var onloginCallback = mockNavigator.id.watch.firstCall.args[0].onlogin;

var assertion = 'browser-id assertion';

onloginCallback(assertion);

equal(

requests[0].requestBody,

$.param({ assertion: assertion, csrfmiddlewaretoken: token }), //

270

|

Chapter 15: User Authentication, Integrating Third-Party Plugins, and Mocking with JavaScript