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

3. I’ve called this object a “mock”, but it’s probably more correctly called a “spy”. We don’t have to concern

ourselves with the differences in this book, but for more on the general class of tools called “Test Doubles”,

including the difference between stubs, mocks, fakes, and spies, see

Mocks, Fakes and Stubs

by Emily Bache.

<script

src=

"http://code.jquery.com/jquery.min.js

"

></script>

<script

src=

"../../../superlists/static/tests/qunit.js"

></script>

<script

src=

"../accounts.js"

></script>

<script>

/*global $, test, equal, sinon, Superlists */

test("initialize binds sign in button to navigator.id.request", function () {

var requestWasCalled = false; //

var mockRequestFunction = function () { requestWasCalled = true; }; //

var mockNavigator = { //

id: {

request: mockRequestFunction

}

};

Superlists.Accounts.initialize(mockNavigator); //

$('#id_login').trigger('click'); //

equal(requestWasCalled, true); //

});

</script>

One of the best ways to understand this test, or indeed any test, is to work backwards.

The first thing we see is the assertion:

We are asserting that a variable called

requestWasCalled

is

true

. We’re checking

that, one way or another, the

request

function, as in

navigator.id.request

,

was called.

Called when? When a click event happens to the

id_login

element.

Before we trigger that click event, we call our

Superlists.Accounts.initial

ize

function, just like we will on the real page. The only difference is, instead of

passing it the real global

navigator

object from Persona, we pass in a fake one

called

mockNavigator

.

3

That’s defined as a generic JavaScript object, with an attribute called

id

which

in turn has an attribute called

request

, which we’re assigning to a variable called

mockRequestFunction

.

mockRequestFunction

we define as a very simple function, which if called will

simply set the value of the

requestWasCalled

variable to

true

.

And finally (firstly?) we make sure that

requestWasCalled

starts out as

false

.

JavaScript Unit Tests Involving External Components: Our First Mocks!

|

259