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

4 assertions of 4 passed, 0 failed.

1. smoke test (0, 2, 2)

2. smoke test 2 (0, 2, 2)

Building a JavaScript Unit Test for Our Desired

Functionality

Now that we’re acquainted with our JavaScript testing tools, we can switch back to just

one test, and start to write the real thing:

lists/static/tests/tests.html.

<script>

/*global $, test, equal */

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

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

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

});

</script>

The jQuery

.trigger

method is mainly used for testing. It says “fire off a

JavScript DOM event on the element(s)”. Here we use the

keypress

event, which

is fired off by the browser behind the scenes whenever a user types something

into a particular input element.

jQuery is hiding a lot of complexity behind the scenes here. Check

out

Quirksmode.org

for a view on the hideous nest of differences

between the different browsers’ interpretation of events. The reason

that jQuery is so popular is that it just makes all this stuff go away.

And that gives us:

0 assertions of 1 passed, 1 failed.

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

1. failed

Expected: false

Result: true

Let’s say we want to keep our code in a standalone JavaScript file called

list.js

.

lists/static/tests/tests.html.

<script

src=

"qunit.js"

></script>

<script

src=

"../list.js"

></script>

<script>

Here’s the minimal code to get that test to pass:

lists/static/list.js.

$

(

'.has-error'

).

hide

();

232

|

Chapter 13: Dipping Our Toes, Very Tentatively, into JavaScript