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

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

test("onlogin post failure should do navigator.id.logout ", function () {

mockNavigator.id.logout = sinon.mock(); //

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

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

var server = sinon.fakeServer.create(); //

server.respondWith([403, {}, "permission denied"]); //

onloginCallback();

equal(mockNavigator.id.logout.called, false, 'should not logout yet');

server.respond(); //

equal(mockNavigator.id.logout.called, true, 'should call logout');

});

We put a mock on the

navigator.id.logout

function which we’re interested

in.

We use Sinon’s

fakeServer

, which is an abstraction on top of the

fakeXMLHtt

pRequest

to simulate Ajax server responses.

We set up our fake server to respond with a 403 “permission denied” response,

to simulate what will happen for unauthorized users.

We then explicitly tell the fake server to send that response. Only then should

we see the logout call.

That gets us to this—a slight change to our spiked code:

accounts/static/accounts.js (ch15l056).

onlogin

:

function

(

assertion

) {

$

.

post

(

urls

.

login

,

{

assertion

:

assertion

,

csrfmiddlewaretoken

:

token

}

).

fail

(

function

() {

navigator

.

id

.

logout

(); });

},

onlogout

:

function

() {}

Finally we add our

window.location.reload

, just to check it doesn’t break any unit

tests:

accounts/static/accounts.js (ch15l057).

navigator

.

id

.

watch

({

loggedInUser

:

user

,

onlogin

:

function

(

assertion

) {

$

.

post

(

urls

.

login

,

{

assertion

:

assertion

,

csrfmiddlewaretoken

:

token

}

)

.

done

(

function

() {

window

.

location

.

reload

(); })

.

fail

(

function

() {

navigator

.

id

.

logout

(); });

},

onlogout

:

function

() {}

});

JavaScript Unit Tests Involving External Components: Our First Mocks!

|

273