JavaScript Testing
Beginner
's
Guide
Test
and
debug
JavaScript
the
easy way
Liang
Yuxian
Eugene
[
rwtmm® Ik
I
I
PUBLISHING
Table
of
Contents
Preface
1Chapter
1:What
isJavaScript Testing?
7Where does
JavaScript
fit intothewebpage?
8HTML Content 8
Time for action-
building
a HTMLdocument 9StylingHTML elementsusingits attributes 11
Specifyingid and classnameforanHTML element 12
Cascading Style
Sheets 12Timefor action -
styling
your HTML documentusing
CSS 14ReferringtoanHTML elementbyits idorclassnameandstylingit 18
Differences betweenaclassselectorandanid selector 19
Otherusesfor dass selectors and id selectors 20
Completelist of CSS attributes 20
JavaScript providing
behavior toa webpage 20Time for action-
giving
behaviorto yourHTML document 20JavaScript Syntax 24
JavaScriptevents 26
Findingelementsinadocument 26
Puttingitall together 28
The difference between
JavaScript
and server-sidelanguages
29Why
pages needtowork withoutJavaScript
30Whatis
testing?
31Why
doyou needto test? 31Types
oferrors 32Loading
errors 33Time for action-
loading
errorsin action 33PartiallycorrectJavaScript 34
Timefor action
-loading
errorsin action 35Runtimeerrors 36
Time for action-runtime errorsin action 36
Table ofContents
Timeforaction-
logic
errors in action 38Someadvice for
writing
error-freeJavaScript
40Always
check forpropernames ofobjects, variables,
and functions 40Check for proper
syntax
40Plan before you code 40
Checkfor correctnessasyou code 40
Preventing
errorsby choosing
a suitabletexteditor 41Summary
41Chapter
2: Ad HocTesting
andDebugging
in
JavaScript
43The purposeof ad hoc
testing-getting
thescript
torun 44What
happens
when the browser encountersan errorinJavaScript
44Browserdifferencesand theneedtotest in
multiple
browsers 45Time for action-
checking
for features andsniffing
browsers 46Testing
browser differences viacapability testing
47Timefor action-
capability
testing
for different browsers 48Are you
getting
thecorrectoutput
andputting
values in thecorrectplaces?
50Accessing
the values on aform 50Time for action-
accessing
valuesfrom
aform 51Anothertechniqueforaccessingform values 54
Accessing
other partsofthe
web page 55Time for action
-getting
thecorrectvalues in thecorrectplaces
55Doesthe
script
give
theexpected
result 65What todo if the
script
doesn't run? 65Visually inspecting
thecode 66Using
alert()
toseewhat code isrunning
66Using alert()
toseewhat values arebeing
used 67Time for action-
using
alerttoinspect
yourcode 67
Aless obtrusiveway tocheck what code is
running
and the values used 71Time for action-
unobtrusively checking
what valuesareused 72Commenting
outparts
of thescript
tosimplify testing
75Timefor action-
simplifying
thechecking
process 76
Timing
differences-making
surethat theHTML is there beforeinteracting
with it 77Why
ad hoctesting
isneverenough
78Summary
79Chapter
3:Syntax
Validation
81The difference between
validating
andtesting
82 Code that is valid butwrong-validation
doesn't find all theerrors 83Code thatisinvalid but
right
83Code thatisinvalid and
wrong-validation
finds
someerrorsthatmight
of
Code
quality
83HTML and CSS needs tobe valid before you start on
JavaScript
84What
happens
if you don'tvalidate yourcode 85Color-coding
editors-how your editorcanhelp
youtospot
validationerrors 87 CommonerrorsinJavaScript
that will bepicked
upby
validation 89JSLint-anonline validator 90
Time for action-
using
JSLint tospot validation errors 91
Valid codeconstructs that
produce
validationwarnings
92Shouldyou
fix
valid code constructsthatproduce
validationwarnings?
92 Whathappens
if you don't fix them 93How tofix validationerrors 93
Error—missing
"use strict" statement 94Time for action
-fixing
"use strict"errors 94Error—unexpected
use of++ 94Time for action-
fixing
the errorof"Unexpected
useof++" 95Error—functionsnotdefined 96
Time for action-
fixing
theerrorof "Functionsnotdefined" 96Too many varstatements 97
Time for action-
fixing
theerrorofusing
too manyvarstatements 98Expecting
<V
instead of<\
100Time foraction-
fixing
theexpectation
of'<V
instead of'</'
101Expected
'===' but found '==' 102Time for action
-changing
==to=== 102Alert isnotdefined 102
Time foraction-
fixing
"Alertis not defined" 103Avoiding
HTML event handlers 103Time for action-
avoiding
HTMLeventhandlers 104Summary
of the correctionswe have done 106JavaScript
Lint-a tool you can download 112Challenge yourself-fix
theremaining
errorsspotted by
JSLint 113Summary
113Chapter
4:Planning
to Test 115A very briefintroductiontothe
software lifecycle
116The
agile
method 116Theagilemethod and the softwarecyclein action 117
Analysisanddesign 117
Implementation
and testing 117Deployment 117
Maintenance 117
TableofContents
When to
develop
the testplan
118 Howmuchtesting
isrequired?
118What is the code intended to do? 119
Testing
whether the code satisfiesour needs 119Testing
for invalid actionsby
users 119A shortsummaryof the
above
issues 120Major
testing concepts
andstrategies
120Functional
requirement testing
120Non-functional
requirement testing
121Acceptance testing
121Black box
testing
122Usabilitytests 123
Boundary
testing 123Equivalence partitioning 123
Betatesting 124
White box
testing
124Branchtesting 124
Paretotesting 125
Unit tests 125
Web pagetests 126
Performancetests 127
Integration testing
127Regression testing-repeating prior testing
aftermaking
changes
128Testing
order 128Documenting
your testplan
129Thetest
plan
129Versioning 130
Teststrategy 130
Bug form 137
Summary
ofourtestplan
137Summary
137Chapter
5:Putting
the Test Plan IntoAction 139Applying
the testplan: running
your tests in order 140Test Case 1:
Testing expected and acceptable
values 140Time for action-Test Case la:
testing expected
andacceptable
valuesby
using
white boxtesting
141TestCase lb:
Testing
expected
butunacceptable
valuesusing
blackboxtesting
142Time for action-Testcase lbi:
testing expected
butunacceptable
valuesusing boundary
valuetesting
142Time foraction-Test
case lbii:
testing expected
butunacceptable
valuesof
Test Case 2:
Testing
the programlogic
146Time for action-
testing
the programlogic
146Test Case 3:
Integration testing and
testing unexpected
values 147 Time for action -Test Case 3a:testing
the entire program withexpected
values 147 Time foraction-Test Case 3b:testing
robustness of the second form 150Whattodo whenatest returns an
unexpected
result 151Regression testing
in action 151Time for action-
fixing
thebugs
andperforming
regression testing
151Performance
issues—compressing
your codetomake it load faster 160 Doesusing Ajax
make a difference? 161Difference from server-side
testing
162What
happens
if youvisitor turnsoffJavaScript
162Summary
164Chapter
6:Testing
MoreComplex
Code165
Issues with
combining scripts
166Combining
eventhandlers 166Naming
clashes 168Using JavaScript
libraries 169Doyou needto test a
library
that someone elsehas written? 170Whatsortoftests to run
against library
code 170Performancetesting 170
Profilingtesting 171
GUI and
widget
add-onstolibraries and considerationson how to testthem 171Deliberately throwing
yourownJavaScript
errors 172The throwstatement 172
The try,
catch,
andfinally
statements 172Trapping
errorsby using
built-inobjects
176The Error
object
176The
RangeError
object
178The ReferenceError
object
178The
TypeError object
180The
SyntaxError object
181The URIError
object
181The EvalError
object
181Using
the errorconsolelog
181Errormessages 181
Writing
yourown messages 182Modifying scripts
andtesting
184 Time for action-coding, modifying, throwing,
andcatching
errors 184TableofContents
Chapter
7:Debugging
Tools
201IE 8
Developer
Tools(and
thedeveloper
toolbarplugin
forIE6and7)
202Using
IEdeveloper
tools 202Open
202A briefintroduction tothe userinterface 203
Debugging
basics of the IEdebugging
tool 203Time foraction
-debugging
HTMLby using
theIE8developer
tool 204Time for action-
debugging
CSSby using
the IE8developer
tool 205Debugging
JavaScript
206Timeforaction-more
Debugging JavaScript by using
the IE8developer
tool 206Safari or
Inspector
andJavaScript Debugger
211Differences between Safari and
Debugging using
Chrome 212A brief introductiontothe userinterface 213
Timeforaction-
debugging
with Chrome 213Opera JavaScript Debugger
(Dragonfly)
218Using Dragonfly
218Starting Dragonfly 218
Time
for
action-debugging
withOpera Dragonfly
219Inspection
and Call Stack 220Thread
Log
220Continue,
Step
Into,Step Over, Step Out,
andStop
at Error 220Settings
222Firefox and theVenkmanextension 222
Using Firefox's
Venkman extension 222 Obtainingthe VenkmanJavaScript Debuggerextension 222OpeningVenkman 222
Abrief introductiontotheuserinterface 223
Time for action
-debugging using
Firefox's Venkman extension 224Breakpoints
orCall Stack 225Local Variables
and
Watches 226Time foraction-more
debugging
with the Venkmanextension 227Firefox andthe
Firebug
extension 229of
Chapter
8:Testing
Tools
231
Sahi 232
Timeforaction- userInterface
testing using
Sahi 232More
complex testing
with Sahi 235QUnit
236Time for action
-testing
JavaScript
withQUnit 236Applying
QUnit
in real-life situations 240More assertion tests forvarioussituations 240
JSLitmus 241
Time foraction-
creating
ad hocJavaScript
benchmark tests 241More
complex testing
with JSLitmus 244More