In addition, we’re using the magic
$
function from jQuery, but sometimes other Java‐
Script libraries try and use that too. It’s just an alias for the less contested name
jQuery
though, so here’s the standard way of getting more fine-grained control over the
namespacing:
lists/static/list.js.
jQuery
(
document
).
ready
(
function
(
$
) {
$
(
'input'
).
on
(
'keypress'
,
function
() {
$
(
'.has-error'
).
hide
();
});
});
Read more in the
jQuery .ready() docs.
We’re almost ready to move on to
Part III. The last step is to deploy our new code to
our servers.
A Few Things That Didn’t Make It
• The selector
$(
input
)
is
way
too greedy; it’s assigning a handler to every input
element on the page. Try the exercise to add a click handler and you’ll realise why
that’s a problem. Make it more discerning!
• At the moment our test only checks that the JavaScript works on one page. It works
because we’re including it in
base.html
, but if we’d only added it to
home.html
the
tests would still pass. It’s a judgement call, but you could choose to write an extra
test here.
JavaScript Testing Notes
• One of the great advantages of Selenium is that it allows you to test that your Java‐
Script really works, just as it tests your Python code.
• There are many JavaScript test running libraries out there. QUnit is closely tied to
jQuery, which is the main reason I chose it.
• QUnit mainly expects you to “run” your tests using an actual web browser. This has
the advantage that it’s easy to create some HTML fixtures that match the kind of
HTML your site actually contains, for tests to run against.
• I don’t really mean it when I say that JavaScript is awful. It can actually be quite fun.
But I’ll say it again: make sure you’ve read
JavaScript: The Good Parts.
A Few Things That Didn’t Make It
|
235