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

6. Sinon also has more specialised objects for “spies” and “stubs”. Mocks can do everything that spies and stubs

can do though, so I figured, one less piece of terminology would keep things simple.

And now we can write a test that uses Sinon’s mock object:

6

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

test

(

"initialize calls navigator.id.watch"

,

function

() {

var

user

=

'current user'

;

var

token

=

'csrf token'

;

var

urls

=

{

login

:

'login url'

,

logout

:

'logout url'

};

var

mockNavigator

=

{

id

:

{

watch

:

sinon

.

mock

()

//

}

};

Superlists

.

Accounts

.

initialize

(

mockNavigator

,

user

,

token

,

urls

);

equal

(

mockNavigator

.

id

.

watch

.

calledOnce

,

//

true

,

'check watch function called'

);

});

We create a mock navigator object as before, but now instead of hand-crafting

a function to mock out the function we’re interested in, we use a

si

non.mock()

object.

This object then records what happens to it inside special properties like

calle

dOnce

, which we can make assertions against.

There’s more info in the Sinon docs—the

front page

actually has quite a good overview.

Here’s our expected test failure:

2 assertions of 3 passed, 1 failed.

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

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

1. check watch function called

Expected: true

Result: false

We add in the call to

watch

accounts/static/accounts.js.

var

initialize

=

function

(

navigator

) {

$

(

'#id_login'

).

on

(

'click'

,

function

() {

navigator

.

id

.

request

();

});

266

|

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