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

It has an obvious problem. We’d better add another test:

lists/static/tests/tests.html.

test("errors should be hidden on keypress", function () {

$('input').trigger('keypress');

equal($('.has-error').is(':visible'), false);

});

test("errors not be hidden unless there is a keypress", function () {

equal($('.has-error').is(':visible'), true);

});

Now we get an expected failure:

1 assertions of 2 passed, 1 failed.

1. errors should be hidden on keypress (0, 1, 1)

2. errors not be hidden unless there is a keypress (1, 0, 1)

1. failed

Expected: true

Result: false

Diff: true false

[...]

And we can make a more realistic implementation:

lists/static/list.js.

$

(

'input'

).

on

(

'keypress'

,

function

() {

//

$

(

'.has-error'

).

hide

();

});

This line says: find all the input elements, and for each of them, attach an event

listener which reacts

on

keypress events. The event listener is the inline function,

which hides all elements that have the class

.has-error

.

That gets our unit tests to pass:

2 assertions of 2 passed, 0 failed.

Grand, so let’s pull in our script, and jQuery, on all our pages:

lists/templates/base.html (ch14l014).

</div>

<script

src=

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

></script>

<script

src=

"/static/list.js"

></script>

</body>

</html>

It’s good practice to put your script-loads at the end of your body

HTML, as it means the user doesn’t have to wait for all your Java‐

Script to load before they can see something on the page. It also helps

to make sure most of the DOM has loaded before any scripts run.

Building a JavaScript Unit Test for Our Desired Functionality

|

233