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

5. Incidentally, notice we use

{{ csrf_token }}

which gives you the raw string token, rather than

{%

csrf_token%}

which would give us a full HTML tag,

<input type="hidden" name="etc etc

.

},

onlogout

:

function

() {

$

.

post

(

'/accounts/logout'

)

.

always

(

function

() {

window

.

location

.

reload

(); });

}

});

Decoding that, the

watch

function needs to know a couple of things from the global

scope:

The current user’s email, to be passed in as the

loggedInUser

parameter to

watch

.

The current CSRF token, to pass in the Ajax POST request to the login view.

5

We’ve also got two hardcoded URLs in there, which would be better to get fromDjango,

something like this:

var

urls

=

{

login

:

"{% url 'login' %}"

,

logout

:

"{% url 'logout' %}"

,

};

So that would be a third parameter to pass in from the global scope. We’ve already got

an

initialize

function, so let’s imagine using it like this:

Superlists

.

Accounts

.

initialize

(

navigator

,

user

,

token

,

urls

);

Using a sinon.js mock to check we call the API correctly

“Rolling your own” mocks is possible as we’ve seen, and JavaScript actually makes it

relatively easy, but using a mocking library can save us a lot of heavy lifting. The most

popular one in the JavaScript world is called

sinon.js

. Let’s download it (from

http:// sinonjs.org )

and put it in our site-wide static tests folder:

$

tree superlists/static/tests/

superlists/static/tests/

├── qunit.css

├── qunit.js

└── sinon.js

Next we include it in our accounts tests:

accounts/static/tests/tests.html.

<script

src=

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

"

></script>

<script

src=

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

></script>

<script

src=

"../../../superlists/static/tests/sinon.js"

></script>

<script

src=

"../accounts.js"

></script>

JavaScript Unit Tests Involving External Components: Our First Mocks!

|

265