1. UK-English speakers may bristle at that incorrect spelling of the word “initialise”. I know, it grates with me
too. But it’s an increasingly accepted convention to use American spelling in code. It makes it easier to search,
for example, and just to work together more generally, if we all agree on how words are spelt. We have to
accept that we’re in the minority here, and this is one battle we’ve probably lost.
2. The new shiny in the JavaScript world for avoiding namespacing problems is called
require.js
. It was one thing
too many to squeeze into this book, but you should check it out.
I had hoped that our first Mock example was going to be in Python,
but it looks like it’s going to be JavaScript instead. Needs must. You
may find you it’s worth rereading the rest of the chapter a couple of
times after you get to the end of it, to let it all sink in.
Namespacing
In the context of
base.html
,
navigator
is just an object in the global scope, as provided
by the
include.js
<script>
tag that we get fromMozilla. Testing global variables is a pain
though, so we can turn it into a local variable by passing it into an “initialize”
1
function.
The code we’ll end up with in
base.html
will look like this:
lists/templates/base.html.
<script
src=
"/static/accounts/accounts.js"
></script>
<script>
$
(
document
).
ready
(
function
() {
Superlists
.
Accounts
.
initialize
(
navigator
)
});
</script>
I’ve specified that our
initialize
function will be
namespaced
inside some nested ob‐
jects,
Superlists.Accounts
. JavaScript suffers from a programming model that’s tied
into a global scope, and this sort of namespacing/naming convention helps to keep
things under control. Lots of JavaScript libraries might want to call a function
initial
ize
, but very few will call it
Superlists.Accounts.initialize
!
2
This call to
initialize
is simple enough that I’m happy it doesn’t need any unit tests
of its own.
A Simple Mock to Unit Tests Our initialize Function
The
initialize
function itself we
will
test. Copy the lists tests across to get the boiler‐
plate HTML, and then adjust the following:
accounts/static/tests/tests.html.
<div
id=
"qunit-fixture"
>
<a
id=
"id_login"
>
Sign in
</a>
</div>
258
|
Chapter 15: User Authentication, Integrating Third-Party Plugins, and Mocking with JavaScript