SlideShare a Scribd company logo
ADVANCED QUNIT
FRONT-END JAVASCRIPT UNIT TESTING
Lars Thorup, ZeaLake / @larsthorup
WHO IS LARS THORUP
Software developer/architect
C#, C++ and JavaScript
Test Driven Development
Coach: Teaching agile and automated testing
Advisor: Assesses software projects and companies
Founder and CEO of ZeaLake
AGENDA
Unit tests gives quality feedback
Make them fast
Make them precise
Run thousands of unit tests in seconds
We will look at
Mocking techniques
Front-end specific testing patterns
Assuming knowledge about JavaScript and unit testing
QUNIT BASICS
m dl (u i. ac l tr ,{
o ue ' tl cl ua o'
s tp f nt o ( {
e u : u ci n )
t i. ac =nw Cl ua o (;
hs cl
e a cl tr )
}
};
)
t s( ml il ' fn to ( {
e t ' u tp y, u ci n )
e ul ti .a c ml il ( , 7 ,4 , ' *' ;
q a (h sc l. ut p y6 ) 2 6 7 )
};
)
MOCKING, SPYING AND STUBBING
WHAT IS HARD TO TEST IN JAVASCRIPT?
HOW TO TEST IN ISOLATION?
We want to test code in isolation
here the code is the 'keypress' event handler
and isolation means not invoking the getMatch() method
' ep es :f nt o (l m n, ee t {
k yr s ' uc in e ee t v n)
v rp te n= t i. lm n. a (;
a at r
h se e etvl )
p te n+ S rn .r m hr oe ee tc a Cd )
a t r = t i gf oC aC d (v n. hr oe ;
v rm th= t i.e Mt hp t en ;
a ac
hsgt a c( at r)
i ( ac){
f m th
e et pe e te al (;
vn .r vn Df u t)
t i . l m n .a ( a c )
hs ee etvl m th ;
}
}
MOCKING METHODS
Using SinonJS
We can mock the getMatch() method
decide how the mock should behave
verify that the mocked method was called correctly
s nn su (u oo p ee ' eM th )r tr s 'o iu ';
i o. t ba tC ml t, g ta c '. eu n( mn q e )
$ 'n m' .r ge ( .v n ( ky r s' {h r oe 1 9) )
(#a e )t ig r $Ee t 'e pe s , c aC d: 0 }; ;
o (u oo pe eg t ac .a ld i h' ')
k at C ml t. eM th c le Wt (m );
e ul $ ' nm '. a (,'o iu ' ;
q a( ( #a e) vl ) m nq e)
MOCKING GLOBAL FUNCTIONS
Global functions are properties of the window object
o eP pp f nt o (r ){
p no u : u ci n ul
v rp pp =w n o. pn ul ' ba k, ' ei al ';
a ou
id wo e (r , _l n' r sz b e)
p pp fc s)
o u .o u( ;
}
v rp pp
a ou;
s nn su (i dw ' pn ,fn to ( {
i o. t bw no , oe ' uc i n )
p pp ={
ou
f cs s nn sy )
ou : i o .p (
}
;
r tr p pp
e u n o u;
};
)
a tC ml t. pn o u( za ae c m)
u oo p ee oe Pp p ' e lk .o ';
o (i dw oe .a l di h' el k .o ' ' b ak,' ei a l' )
k wn o .p nc le Wt ( za ae cm , _l n' rs zb e) ;
o (o u. ou .a l d ' o u c a gd)
k pp p fc sc le , fc s hn e';
MOCKING CONSTRUCTORS
Constructors are functions
with t i being the object to construct
hs
t i. nu = nw wn o . u oo pe ei pt l mn ,{
h si p t
e i dw At Cm l t( nu Ee et
l sU l ti .p in . it r
i t r: hs o to sl sU l
};
)
t i. nu .o u ( ;
h si p tf cs )
s nn su (i dw ' uo o pe e, fn to ( {
i o. t bw no , At Cm lt ' u ci n )
t i. ou = sn ns y )
h s fc s
i o. p( ;
};
)
o (o m 'r ae ';
k fr , ce td )
e ul wn o. uo o pe ec lC u t 1;
q a( i dw At Cm lt . al on , )
v ra g =w no .u oo p ee fr ta lc l .r s
a rs
i dw A tC ml t. i sC l. al ag ;
o (r s0. s 'n m ')
k ag []i(# ae );
d eE ul ag [ ] { it r :' sm Ul };
e pq a (r s1 , ls Ul / o er ')
v ra tC ml t =w no . uo op ee fr t al cl .h s au ;
a u o op ee
id wA tC m lt .i sC l. a lt iV le
o (u oo pe ef c sc le )
k at C ml t. ou .a l d;
HOW TO AVOID WAITING?
We want the tests to be fast
So don't use Jasmine w i s o (
atFr)
But we often need to wait
For animations to complete
For AJAX responses to return
d ly ie f nt o ( {
e aH d : u ci n )
v rs l =t i;
a ef
hs
s ti eu (u c in( {
e T mo tf nt o )
s l. lm n .i e)
ef ee et hd ( ;
} t i. pi n. ie e a)
, h so to s hd Dl y;
}
MOCKING TIMERS
Use Sinon's mock clock
Tick the clock explicitly
Now the test completes in milliseconds
without waiting
s nn ue ae ie s )
i o. s Fk Tm r( ;
a tC ml t. ea H d( ;
u oo p ee dl yi e)
o (( #a e) i (: ii l' )
k $ ' n m' .s 'v sb e );
s nn co kt c( 0 )
i o. l c. ik 50 ;
o (( #a e) i (: id n) ;
k $ ' n m' .s 'h de ' )
MOCKING TIME
n w D t ( tends to return different values over time
e ae)
...actually, that's the whole point :)
But how do we test code that relies on that?
We cannot e u l a value that changes on every run
q a on
Instead, Sinon can mock the D t ( constructor!
ae)
s nn ue ae ie s )
i o. s Fk Tm r( ;
v rt e =n wD t( ;
a hn
e ae)
s nn co kt c( 2 0)
i o. l c. ik 40 0;
v rl tr = n wD t (;
a ae
e ae )
e ul lt rg ti e )- te .e T m( ,4 00;
q a( a e. eT m(
h ng ti e) 2 0)
MOCKING AJAX REQUESTS
To test in isolation
To vastly speed up the tests
Many options
can.fixture
Mockjax
Sinon
c nf xu e' gt a e' f nt o (r gn l rs od ih {
a .i t r( /e Nm s, u ci n oi ia , ep n Wt )
r so di h{ i t [ r ce '} ;
e p nW t( ls : 'a hl ] )
};
)
v ra tC ml t = n wA t Cm lt (# ae , {
a u o op ee
e uo op e e' nm '
l sU l 'g ta e'
i t r: /e N ms
};
)
s nn co kt c( a .i tr .e a )
i o. l c. ik cn fx u ed ly ;
r so di h5 0; / It r a s r e e rr
e pn W t( 0) / n en l ev r ro
DOM FIXTURES
Supply the markup required by the code
Automatically cleanup markup after every test
Built into QUnit as #qunit-fixture
$ 'i pt i=nm " '. pe do ' qn tf xu e)
( <n u d "a e >)a p nT (# ui -i t r' ;
a tC ml t =n wA tC m lt (# ae )
u oo p ee
e uo op ee ' nm ';
SPYING ON EVENTS
How do we test that an event was cancelled?
Spy on the preventDefault() method
' ep es :f nt o (l m n, ee t {
k yr s ' uc in e ee t v n)
v rp te n= t i. lm n. a ( +
a at r
h se e etvl )
Sr n .r mh ro ee e tc aC d)
t ig fo Ca C d( vn .h r oe ;
v rm th= t i.e Mt hp t en ;
a ac
hsgt a c( at r)
i(a c) {
f m th
e et pe e te al (;
vn .r vn Df u t)
t i . l m n .a ( a c )
hs ee etvl m th ;
}
}
v rk yr sE et = $ E et 'e p es ,{ hr oe 1 9)
a e p es vn
. v n (k yr s' c a Cd : 0} ;
s nn sy ky rs E et ' rv nD fu t)
i o. p (e pe sv n, p ee t ea l' ;
$'n m' .r ge ( ep es vn )
(#a e )t ig rk yr s Ee t;
o (e pe sv n. r vn Df ut c le )
k ky r sE et pe et e al .a ld ;
SIMULATING CSS TRANSITIONS
PARAMERIZED AND CONDITIONED TESTS
Some code is browser specific
maybe using a browser specific API
and might only be testable in that browser
Tests can be conditioned
Or iterated...
c ne c(
a .a h [
{ ec ' uc s' r so s: { it [x ] ,e pc e: [ x] ,
d s : s ce s , e p ne l s: ' '} x e td ' '}
{ ec ' al r' r so s: 5 0 e pc e :[ }
d s : f iu e, e p ne 0 , xe td ]
] fn t o ( cn r o {
, u ci n se ai )
t s(ls Ul o to ,' +s e ai .e c fn to ( {
e t'i tr p in
cn ro ds , uc i n )
c nf xu e 'g ta e' f nt o (r gn l rs o di h {
a. it r( /e N ms , uc in o ii a, e pn Wt )
r so d ih se ai . ep ne ;
ep nW t( c nr or so s)
};
)
d eE ul a tC ml t. p in .i t se ai .x e td ;
ep qa (u oo p ee ot os ls , cn r oe pc e)
};
)
};
)
LEAK DETECTION
DOM ELEMENT LEAKS
DOM Fixtures are cleaned up automatically
But sometimes code needs to go beyond the fixture,
appending to $('body'), e.g for overlays
That code should have a way to clean up those elements
And our tests should invoke that cleanup
And we can easily verify that this is always done
t ad w: fn to ( {
e ro n u ci n )
v rl as =$ ' oy )c id e (: o( qn tr p re ) )
a ek
(b d' . hl rn 'n t# u i- eo tr ' ;
e ul la sl n t, 0 'o DM ee et l ae ' ;
q a (e k. eg h , n O l mn s ek d )
l as rm v( ;
e k .e oe )
}
MEMORY LEAKS
window.performance.memory: a Google Chrome extension
run Chrome with --enable-memory-info --js-flags="--exposegc"
Collect memory consumption data for every test
Sort and investigate the largest memory consumers
However, performance data is not reproducible
And the garbage collector disturbs the picture
But still usable
s tp f nt o ( {
e u: u ci n )
w no .c )
i d wg (;
t i. ep ie e oe =w no. ef ra c. eo y ue JH aS z;
h s ha Sz Bf r
i d wp r o m n e m m r. s d S e p i e
}
,
t ad w: fn to ( {
e ro n u ci n )
w no .c )
i d wg (;
t i. ep ie f e = w no.e fr ac . eo yu eJ H aS z;
h s ha Sz At r
i dwp ro mn em mr . sd Se pi e
c no el gs e.e pi ef e -s e . e pi ee oe;
o s l. o( pcha S zA tr
pc ha Sz B fr)
}
RESOURCES
github.com/larsthorup/qunit-demo-advanced
@larsthorup
qunitjs.com
sinonjs.com
canjs.com
github.com/hakimel/reveal.js

More Related Content

What's hot

Menu Driven programs in Java
Menu Driven programs in JavaMenu Driven programs in Java
Menu Driven programs in Java
Lakshmi Sarvani Videla
 
Introduction to Ansible
Introduction to AnsibleIntroduction to Ansible
Introduction to Ansible
Mattias Gees
 
CROCHET - Checkpoint Rollback in JVM (ECOOP 2018)
CROCHET - Checkpoint Rollback in JVM (ECOOP 2018)CROCHET - Checkpoint Rollback in JVM (ECOOP 2018)
CROCHET - Checkpoint Rollback in JVM (ECOOP 2018)
jon_bell
 
Nipype
NipypeNipype
Nipype
PyData
 
TMPA-2017: Predicate Abstraction Based Configurable Method for Data Race Dete...
TMPA-2017: Predicate Abstraction Based Configurable Method for Data Race Dete...TMPA-2017: Predicate Abstraction Based Configurable Method for Data Race Dete...
TMPA-2017: Predicate Abstraction Based Configurable Method for Data Race Dete...
Iosif Itkin
 
Lenguaje ensamblador EMU8086
Lenguaje ensamblador EMU8086Lenguaje ensamblador EMU8086
Lenguaje ensamblador EMU8086
Santy Bolo
 
Lock? We don't need no stinkin' locks!
Lock? We don't need no stinkin' locks!Lock? We don't need no stinkin' locks!
Lock? We don't need no stinkin' locks!
Michael Barker
 
chapter 2 Java at rupp cambodia
chapter 2 Java at rupp cambodiachapter 2 Java at rupp cambodia
chapter 2 Java at rupp cambodia
Sami Mut
 
Emulador de ensamblador EMU8086
Emulador de ensamblador EMU8086Emulador de ensamblador EMU8086
Emulador de ensamblador EMU8086
Jhon Alexito
 
2013-02-21 - .NET UG Rhein-Neckar: JavaScript Best Practices
2013-02-21 - .NET UG Rhein-Neckar: JavaScript Best Practices2013-02-21 - .NET UG Rhein-Neckar: JavaScript Best Practices
2013-02-21 - .NET UG Rhein-Neckar: JavaScript Best Practices
Johannes Hoppe
 
Javascript: The Important Bits
Javascript: The Important BitsJavascript: The Important Bits
Javascript: The Important Bits
Zumba Fitness - Technology Team
 
Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.
Platonov Sergey
 
Pasos para simular una mss en vhdl
Pasos para simular una mss en vhdlPasos para simular una mss en vhdl
Pasos para simular una mss en vhdl
Ivan Salazar C
 
โปรแกรมย่อยและฟังชันก์มาตรฐาน
โปรแกรมย่อยและฟังชันก์มาตรฐานโปรแกรมย่อยและฟังชันก์มาตรฐาน
โปรแกรมย่อยและฟังชันก์มาตรฐาน
knang
 
Mauro yaguachi
Mauro yaguachiMauro yaguachi
Mauro yaguachi
MAUROYAGAUCHI
 
C Language - Switch and For Loop
C Language - Switch and For LoopC Language - Switch and For Loop
C Language - Switch and For Loop
Sukrit Gupta
 
Math in V8 is Broken and How We Can Fix It - Athan Reines, Fourier
Math in V8 is Broken and How We Can Fix It - Athan Reines, FourierMath in V8 is Broken and How We Can Fix It - Athan Reines, Fourier
Math in V8 is Broken and How We Can Fix It - Athan Reines, Fourier
NodejsFoundation
 
The Ring programming language version 1.5.1 book - Part 8 of 180
The Ring programming language version 1.5.1 book - Part 8 of 180The Ring programming language version 1.5.1 book - Part 8 of 180
The Ring programming language version 1.5.1 book - Part 8 of 180
Mahmoud Samir Fayed
 
The Ring programming language version 1.5.3 book - Part 9 of 184
The Ring programming language version 1.5.3 book - Part 9 of 184The Ring programming language version 1.5.3 book - Part 9 of 184
The Ring programming language version 1.5.3 book - Part 9 of 184
Mahmoud Samir Fayed
 
Singly Linked List
Singly Linked ListSingly Linked List
Singly Linked List
Er. Ganesh Ram Suwal
 

What's hot (20)

Menu Driven programs in Java
Menu Driven programs in JavaMenu Driven programs in Java
Menu Driven programs in Java
 
Introduction to Ansible
Introduction to AnsibleIntroduction to Ansible
Introduction to Ansible
 
CROCHET - Checkpoint Rollback in JVM (ECOOP 2018)
CROCHET - Checkpoint Rollback in JVM (ECOOP 2018)CROCHET - Checkpoint Rollback in JVM (ECOOP 2018)
CROCHET - Checkpoint Rollback in JVM (ECOOP 2018)
 
Nipype
NipypeNipype
Nipype
 
TMPA-2017: Predicate Abstraction Based Configurable Method for Data Race Dete...
TMPA-2017: Predicate Abstraction Based Configurable Method for Data Race Dete...TMPA-2017: Predicate Abstraction Based Configurable Method for Data Race Dete...
TMPA-2017: Predicate Abstraction Based Configurable Method for Data Race Dete...
 
Lenguaje ensamblador EMU8086
Lenguaje ensamblador EMU8086Lenguaje ensamblador EMU8086
Lenguaje ensamblador EMU8086
 
Lock? We don't need no stinkin' locks!
Lock? We don't need no stinkin' locks!Lock? We don't need no stinkin' locks!
Lock? We don't need no stinkin' locks!
 
chapter 2 Java at rupp cambodia
chapter 2 Java at rupp cambodiachapter 2 Java at rupp cambodia
chapter 2 Java at rupp cambodia
 
Emulador de ensamblador EMU8086
Emulador de ensamblador EMU8086Emulador de ensamblador EMU8086
Emulador de ensamblador EMU8086
 
2013-02-21 - .NET UG Rhein-Neckar: JavaScript Best Practices
2013-02-21 - .NET UG Rhein-Neckar: JavaScript Best Practices2013-02-21 - .NET UG Rhein-Neckar: JavaScript Best Practices
2013-02-21 - .NET UG Rhein-Neckar: JavaScript Best Practices
 
Javascript: The Important Bits
Javascript: The Important BitsJavascript: The Important Bits
Javascript: The Important Bits
 
Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.
 
Pasos para simular una mss en vhdl
Pasos para simular una mss en vhdlPasos para simular una mss en vhdl
Pasos para simular una mss en vhdl
 
โปรแกรมย่อยและฟังชันก์มาตรฐาน
โปรแกรมย่อยและฟังชันก์มาตรฐานโปรแกรมย่อยและฟังชันก์มาตรฐาน
โปรแกรมย่อยและฟังชันก์มาตรฐาน
 
Mauro yaguachi
Mauro yaguachiMauro yaguachi
Mauro yaguachi
 
C Language - Switch and For Loop
C Language - Switch and For LoopC Language - Switch and For Loop
C Language - Switch and For Loop
 
Math in V8 is Broken and How We Can Fix It - Athan Reines, Fourier
Math in V8 is Broken and How We Can Fix It - Athan Reines, FourierMath in V8 is Broken and How We Can Fix It - Athan Reines, Fourier
Math in V8 is Broken and How We Can Fix It - Athan Reines, Fourier
 
The Ring programming language version 1.5.1 book - Part 8 of 180
The Ring programming language version 1.5.1 book - Part 8 of 180The Ring programming language version 1.5.1 book - Part 8 of 180
The Ring programming language version 1.5.1 book - Part 8 of 180
 
The Ring programming language version 1.5.3 book - Part 9 of 184
The Ring programming language version 1.5.3 book - Part 9 of 184The Ring programming language version 1.5.3 book - Part 9 of 184
The Ring programming language version 1.5.3 book - Part 9 of 184
 
Singly Linked List
Singly Linked ListSingly Linked List
Singly Linked List
 

Viewers also liked

Qunit Java script Un
Qunit Java script UnQunit Java script Un
Qunit Java script Un
akanksha arora
 
Stop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScriptStop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScript
Ryan Anklam
 
Automated Testing in EmberJS
Automated Testing in EmberJSAutomated Testing in EmberJS
Automated Testing in EmberJS
Ben Limmer
 
Javascript Unit Testting (PHPBenelux 2011-05-04)
Javascript Unit Testting (PHPBenelux 2011-05-04)Javascript Unit Testting (PHPBenelux 2011-05-04)
Javascript Unit Testting (PHPBenelux 2011-05-04)
Tom Van Herreweghe
 
JavaScript Unit Testing
JavaScript Unit TestingJavaScript Unit Testing
JavaScript Unit Testing
Christian Johansen
 
JavaScript Test-Driven Development (TDD) with QUnit
JavaScript Test-Driven Development (TDD) with QUnitJavaScript Test-Driven Development (TDD) with QUnit
JavaScript Test-Driven Development (TDD) with QUnit
Tasanakorn Phaipool
 
Unit Testing in JavaScript with MVC and QUnit
Unit Testing in JavaScript with MVC and QUnitUnit Testing in JavaScript with MVC and QUnit
Unit Testing in JavaScript with MVC and QUnit
Lars Thorup
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testing
jeresig
 
Vuejs testing
Vuejs testingVuejs testing
Vuejs testing
Greg TAPPERO
 
Automated Web Testing using JavaScript
Automated Web Testing using JavaScriptAutomated Web Testing using JavaScript
Automated Web Testing using JavaScript
Simon Guest
 

Viewers also liked (10)

Qunit Java script Un
Qunit Java script UnQunit Java script Un
Qunit Java script Un
 
Stop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScriptStop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScript
 
Automated Testing in EmberJS
Automated Testing in EmberJSAutomated Testing in EmberJS
Automated Testing in EmberJS
 
Javascript Unit Testting (PHPBenelux 2011-05-04)
Javascript Unit Testting (PHPBenelux 2011-05-04)Javascript Unit Testting (PHPBenelux 2011-05-04)
Javascript Unit Testting (PHPBenelux 2011-05-04)
 
JavaScript Unit Testing
JavaScript Unit TestingJavaScript Unit Testing
JavaScript Unit Testing
 
JavaScript Test-Driven Development (TDD) with QUnit
JavaScript Test-Driven Development (TDD) with QUnitJavaScript Test-Driven Development (TDD) with QUnit
JavaScript Test-Driven Development (TDD) with QUnit
 
Unit Testing in JavaScript with MVC and QUnit
Unit Testing in JavaScript with MVC and QUnitUnit Testing in JavaScript with MVC and QUnit
Unit Testing in JavaScript with MVC and QUnit
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testing
 
Vuejs testing
Vuejs testingVuejs testing
Vuejs testing
 
Automated Web Testing using JavaScript
Automated Web Testing using JavaScriptAutomated Web Testing using JavaScript
Automated Web Testing using JavaScript
 

Similar to Advanced QUnit - Front-End JavaScript Unit Testing

JavaFX, because you're worth it
JavaFX, because you're worth itJavaFX, because you're worth it
JavaFX, because you're worth it
Thierry Wasylczenko
 
Testing Fuse Fabric with Pax Exam
Testing Fuse Fabric with Pax ExamTesting Fuse Fabric with Pax Exam
Testing Fuse Fabric with Pax Exam
Henryk Konsek
 
Spring scala - Sneaking Scala into your corporation
Spring scala  - Sneaking Scala into your corporationSpring scala  - Sneaking Scala into your corporation
Spring scala - Sneaking Scala into your corporation
Henryk Konsek
 
Code GPU with CUDA - Identifying performance limiters
Code GPU with CUDA - Identifying performance limitersCode GPU with CUDA - Identifying performance limiters
Code GPU with CUDA - Identifying performance limiters
Marina Kolpakova
 
Automated tests - facts and myths
Automated tests - facts and mythsAutomated tests - facts and myths
Automated tests - facts and myths
Wojciech Sznapka
 
Time brings all things to pass
Time brings all things to passTime brings all things to pass
Time brings all things to pass
Kamil Witecki
 
One page app with AngularJS
One page app with AngularJSOne page app with AngularJS
One page app with AngularJS
Adam Štipák
 
Building modern web apps with html5, javascript, and java
Building modern web apps with html5, javascript, and javaBuilding modern web apps with html5, javascript, and java
Building modern web apps with html5, javascript, and java
Alexander Gyoshev
 
Ember js meetup treviso liquid-fire
Ember js meetup treviso liquid-fireEmber js meetup treviso liquid-fire
Ember js meetup treviso liquid-fire
William Bergamo
 
GraphQL Relay Introduction
GraphQL Relay IntroductionGraphQL Relay Introduction
GraphQL Relay Introduction
Chen-Tsu Lin
 
Introduction to Compiler Development
Introduction to Compiler DevelopmentIntroduction to Compiler Development
Introduction to Compiler Development
Logan Chien
 
javapravticalfile.doc
javapravticalfile.docjavapravticalfile.doc
javapravticalfile.doc
PrinceSaini209948
 
Beginner workshop to angularjs presentation at Google
Beginner workshop to angularjs presentation at GoogleBeginner workshop to angularjs presentation at Google
Beginner workshop to angularjs presentation at Google
Ari Lerner
 
Learn Frontend Testing
Learn Frontend TestingLearn Frontend Testing
Learn Frontend Testing
Ryan Roemer
 
An Introduction to CSS Preprocessors
An Introduction to CSS PreprocessorsAn Introduction to CSS Preprocessors
An Introduction to CSS Preprocessors
Miloš Sutanovac
 
Improving Software Reliability via Mining Software Engineering Data
Improving Software Reliability via Mining Software Engineering DataImproving Software Reliability via Mining Software Engineering Data
Improving Software Reliability via Mining Software Engineering Data
Tao Xie
 
Architecting Android Apps: Marko Gargenta
Architecting Android Apps: Marko GargentaArchitecting Android Apps: Marko Gargenta
Architecting Android Apps: Marko Gargenta
jaxconf
 
Flow of events during Media Player creation in Android
Flow of events during Media Player creation in AndroidFlow of events during Media Player creation in Android
Flow of events during Media Player creation in Android
Somenath Mukhopadhyay
 
TensorFlow 2: New Era of Developing Deep Learning Models
TensorFlow 2: New Era of Developing Deep Learning ModelsTensorFlow 2: New Era of Developing Deep Learning Models
TensorFlow 2: New Era of Developing Deep Learning Models
Jeongkyu Shin
 
Writing (Meteor) Code With Style
Writing (Meteor) Code With StyleWriting (Meteor) Code With Style
Writing (Meteor) Code With Style
Stephan Hochhaus
 

Similar to Advanced QUnit - Front-End JavaScript Unit Testing (20)

JavaFX, because you're worth it
JavaFX, because you're worth itJavaFX, because you're worth it
JavaFX, because you're worth it
 
Testing Fuse Fabric with Pax Exam
Testing Fuse Fabric with Pax ExamTesting Fuse Fabric with Pax Exam
Testing Fuse Fabric with Pax Exam
 
Spring scala - Sneaking Scala into your corporation
Spring scala  - Sneaking Scala into your corporationSpring scala  - Sneaking Scala into your corporation
Spring scala - Sneaking Scala into your corporation
 
Code GPU with CUDA - Identifying performance limiters
Code GPU with CUDA - Identifying performance limitersCode GPU with CUDA - Identifying performance limiters
Code GPU with CUDA - Identifying performance limiters
 
Automated tests - facts and myths
Automated tests - facts and mythsAutomated tests - facts and myths
Automated tests - facts and myths
 
Time brings all things to pass
Time brings all things to passTime brings all things to pass
Time brings all things to pass
 
One page app with AngularJS
One page app with AngularJSOne page app with AngularJS
One page app with AngularJS
 
Building modern web apps with html5, javascript, and java
Building modern web apps with html5, javascript, and javaBuilding modern web apps with html5, javascript, and java
Building modern web apps with html5, javascript, and java
 
Ember js meetup treviso liquid-fire
Ember js meetup treviso liquid-fireEmber js meetup treviso liquid-fire
Ember js meetup treviso liquid-fire
 
GraphQL Relay Introduction
GraphQL Relay IntroductionGraphQL Relay Introduction
GraphQL Relay Introduction
 
Introduction to Compiler Development
Introduction to Compiler DevelopmentIntroduction to Compiler Development
Introduction to Compiler Development
 
javapravticalfile.doc
javapravticalfile.docjavapravticalfile.doc
javapravticalfile.doc
 
Beginner workshop to angularjs presentation at Google
Beginner workshop to angularjs presentation at GoogleBeginner workshop to angularjs presentation at Google
Beginner workshop to angularjs presentation at Google
 
Learn Frontend Testing
Learn Frontend TestingLearn Frontend Testing
Learn Frontend Testing
 
An Introduction to CSS Preprocessors
An Introduction to CSS PreprocessorsAn Introduction to CSS Preprocessors
An Introduction to CSS Preprocessors
 
Improving Software Reliability via Mining Software Engineering Data
Improving Software Reliability via Mining Software Engineering DataImproving Software Reliability via Mining Software Engineering Data
Improving Software Reliability via Mining Software Engineering Data
 
Architecting Android Apps: Marko Gargenta
Architecting Android Apps: Marko GargentaArchitecting Android Apps: Marko Gargenta
Architecting Android Apps: Marko Gargenta
 
Flow of events during Media Player creation in Android
Flow of events during Media Player creation in AndroidFlow of events during Media Player creation in Android
Flow of events during Media Player creation in Android
 
TensorFlow 2: New Era of Developing Deep Learning Models
TensorFlow 2: New Era of Developing Deep Learning ModelsTensorFlow 2: New Era of Developing Deep Learning Models
TensorFlow 2: New Era of Developing Deep Learning Models
 
Writing (Meteor) Code With Style
Writing (Meteor) Code With StyleWriting (Meteor) Code With Style
Writing (Meteor) Code With Style
 

More from Lars Thorup

100 tests per second - 40 releases per week
100 tests per second - 40 releases per week100 tests per second - 40 releases per week
100 tests per second - 40 releases per week
Lars Thorup
 
SQL or NoSQL - how to choose
SQL or NoSQL - how to chooseSQL or NoSQL - how to choose
SQL or NoSQL - how to choose
Lars Thorup
 
Super fast end-to-end-tests
Super fast end-to-end-testsSuper fast end-to-end-tests
Super fast end-to-end-tests
Lars Thorup
 
Extreme Programming - to the next-level
Extreme Programming - to the next-levelExtreme Programming - to the next-level
Extreme Programming - to the next-level
Lars Thorup
 
Advanced Javascript Unit Testing
Advanced Javascript Unit TestingAdvanced Javascript Unit Testing
Advanced Javascript Unit Testing
Lars Thorup
 
Unit testing legacy code
Unit testing legacy codeUnit testing legacy code
Unit testing legacy code
Lars Thorup
 
Put "fast" back in "fast feedback"
Put "fast" back in "fast feedback"Put "fast" back in "fast feedback"
Put "fast" back in "fast feedback"
Lars Thorup
 
Database Schema Evolution
Database Schema EvolutionDatabase Schema Evolution
Database Schema Evolution
Lars Thorup
 
Advanced Jasmine - Front-End JavaScript Unit Testing
Advanced Jasmine - Front-End JavaScript Unit TestingAdvanced Jasmine - Front-End JavaScript Unit Testing
Advanced Jasmine - Front-End JavaScript Unit Testing
Lars Thorup
 
Javascript unit testing with QUnit and Sinon
Javascript unit testing with QUnit and SinonJavascript unit testing with QUnit and Sinon
Javascript unit testing with QUnit and Sinon
Lars Thorup
 
Continuous Integration for front-end JavaScript
Continuous Integration for front-end JavaScriptContinuous Integration for front-end JavaScript
Continuous Integration for front-end JavaScript
Lars Thorup
 
Automated Performance Testing
Automated Performance TestingAutomated Performance Testing
Automated Performance Testing
Lars Thorup
 
Test and Behaviour Driven Development (TDD/BDD)
Test and Behaviour Driven Development (TDD/BDD)Test and Behaviour Driven Development (TDD/BDD)
Test and Behaviour Driven Development (TDD/BDD)
Lars Thorup
 
Agile Contracts
Agile ContractsAgile Contracts
Agile Contracts
Lars Thorup
 
High Performance Software Engineering Teams
High Performance Software Engineering TeamsHigh Performance Software Engineering Teams
High Performance Software Engineering Teams
Lars Thorup
 
Elephant Carpaccio
Elephant CarpaccioElephant Carpaccio
Elephant Carpaccio
Lars Thorup
 
Automated Testing for Embedded Software in C or C++
Automated Testing for Embedded Software in C or C++Automated Testing for Embedded Software in C or C++
Automated Testing for Embedded Software in C or C++
Lars Thorup
 
Introduction to Automated Testing
Introduction to Automated TestingIntroduction to Automated Testing
Introduction to Automated Testing
Lars Thorup
 

More from Lars Thorup (18)

100 tests per second - 40 releases per week
100 tests per second - 40 releases per week100 tests per second - 40 releases per week
100 tests per second - 40 releases per week
 
SQL or NoSQL - how to choose
SQL or NoSQL - how to chooseSQL or NoSQL - how to choose
SQL or NoSQL - how to choose
 
Super fast end-to-end-tests
Super fast end-to-end-testsSuper fast end-to-end-tests
Super fast end-to-end-tests
 
Extreme Programming - to the next-level
Extreme Programming - to the next-levelExtreme Programming - to the next-level
Extreme Programming - to the next-level
 
Advanced Javascript Unit Testing
Advanced Javascript Unit TestingAdvanced Javascript Unit Testing
Advanced Javascript Unit Testing
 
Unit testing legacy code
Unit testing legacy codeUnit testing legacy code
Unit testing legacy code
 
Put "fast" back in "fast feedback"
Put "fast" back in "fast feedback"Put "fast" back in "fast feedback"
Put "fast" back in "fast feedback"
 
Database Schema Evolution
Database Schema EvolutionDatabase Schema Evolution
Database Schema Evolution
 
Advanced Jasmine - Front-End JavaScript Unit Testing
Advanced Jasmine - Front-End JavaScript Unit TestingAdvanced Jasmine - Front-End JavaScript Unit Testing
Advanced Jasmine - Front-End JavaScript Unit Testing
 
Javascript unit testing with QUnit and Sinon
Javascript unit testing with QUnit and SinonJavascript unit testing with QUnit and Sinon
Javascript unit testing with QUnit and Sinon
 
Continuous Integration for front-end JavaScript
Continuous Integration for front-end JavaScriptContinuous Integration for front-end JavaScript
Continuous Integration for front-end JavaScript
 
Automated Performance Testing
Automated Performance TestingAutomated Performance Testing
Automated Performance Testing
 
Test and Behaviour Driven Development (TDD/BDD)
Test and Behaviour Driven Development (TDD/BDD)Test and Behaviour Driven Development (TDD/BDD)
Test and Behaviour Driven Development (TDD/BDD)
 
Agile Contracts
Agile ContractsAgile Contracts
Agile Contracts
 
High Performance Software Engineering Teams
High Performance Software Engineering TeamsHigh Performance Software Engineering Teams
High Performance Software Engineering Teams
 
Elephant Carpaccio
Elephant CarpaccioElephant Carpaccio
Elephant Carpaccio
 
Automated Testing for Embedded Software in C or C++
Automated Testing for Embedded Software in C or C++Automated Testing for Embedded Software in C or C++
Automated Testing for Embedded Software in C or C++
 
Introduction to Automated Testing
Introduction to Automated TestingIntroduction to Automated Testing
Introduction to Automated Testing
 

Recently uploaded

Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
akankshawande
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
Jakub Marek
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
Jason Packer
 
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
saastr
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
Javier Junquera
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Tosin Akinosho
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
panagenda
 
Essentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation ParametersEssentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation Parameters
Safe Software
 
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
saastr
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
Edge AI and Vision Alliance
 
Y-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PPY-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PP
c5vrf27qcz
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota
Fwdays
 
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
Jason Yip
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
saastr
 
Dandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity serverDandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity server
Antonios Katsarakis
 
Apps Break Data
Apps Break DataApps Break Data
Apps Break Data
Ivo Velitchkov
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
Tatiana Kojar
 
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Pitangent Analytics & Technology Solutions Pvt. Ltd
 
What is an RPA CoE? Session 1 – CoE Vision
What is an RPA CoE?  Session 1 – CoE VisionWhat is an RPA CoE?  Session 1 – CoE Vision
What is an RPA CoE? Session 1 – CoE Vision
DianaGray10
 

Recently uploaded (20)

Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
 
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
 
Essentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation ParametersEssentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation Parameters
 
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
 
Y-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PPY-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PP
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
 
"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota
 
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
 
Dandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity serverDandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity server
 
Apps Break Data
Apps Break DataApps Break Data
Apps Break Data
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
 
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
 
What is an RPA CoE? Session 1 – CoE Vision
What is an RPA CoE?  Session 1 – CoE VisionWhat is an RPA CoE?  Session 1 – CoE Vision
What is an RPA CoE? Session 1 – CoE Vision
 

Advanced QUnit - Front-End JavaScript Unit Testing

  • 1. ADVANCED QUNIT FRONT-END JAVASCRIPT UNIT TESTING Lars Thorup, ZeaLake / @larsthorup
  • 2. WHO IS LARS THORUP Software developer/architect C#, C++ and JavaScript Test Driven Development Coach: Teaching agile and automated testing Advisor: Assesses software projects and companies Founder and CEO of ZeaLake
  • 3. AGENDA Unit tests gives quality feedback Make them fast Make them precise Run thousands of unit tests in seconds We will look at Mocking techniques Front-end specific testing patterns Assuming knowledge about JavaScript and unit testing
  • 4. QUNIT BASICS m dl (u i. ac l tr ,{ o ue ' tl cl ua o' s tp f nt o ( { e u : u ci n ) t i. ac =nw Cl ua o (; hs cl e a cl tr ) } }; ) t s( ml il ' fn to ( { e t ' u tp y, u ci n ) e ul ti .a c ml il ( , 7 ,4 , ' *' ; q a (h sc l. ut p y6 ) 2 6 7 ) }; )
  • 6. WHAT IS HARD TO TEST IN JAVASCRIPT?
  • 7. HOW TO TEST IN ISOLATION? We want to test code in isolation here the code is the 'keypress' event handler and isolation means not invoking the getMatch() method ' ep es :f nt o (l m n, ee t { k yr s ' uc in e ee t v n) v rp te n= t i. lm n. a (; a at r h se e etvl ) p te n+ S rn .r m hr oe ee tc a Cd ) a t r = t i gf oC aC d (v n. hr oe ; v rm th= t i.e Mt hp t en ; a ac hsgt a c( at r) i ( ac){ f m th e et pe e te al (; vn .r vn Df u t) t i . l m n .a ( a c ) hs ee etvl m th ; } }
  • 8. MOCKING METHODS Using SinonJS We can mock the getMatch() method decide how the mock should behave verify that the mocked method was called correctly s nn su (u oo p ee ' eM th )r tr s 'o iu '; i o. t ba tC ml t, g ta c '. eu n( mn q e ) $ 'n m' .r ge ( .v n ( ky r s' {h r oe 1 9) ) (#a e )t ig r $Ee t 'e pe s , c aC d: 0 }; ; o (u oo pe eg t ac .a ld i h' ') k at C ml t. eM th c le Wt (m ); e ul $ ' nm '. a (,'o iu ' ; q a( ( #a e) vl ) m nq e)
  • 9. MOCKING GLOBAL FUNCTIONS Global functions are properties of the window object o eP pp f nt o (r ){ p no u : u ci n ul v rp pp =w n o. pn ul ' ba k, ' ei al '; a ou id wo e (r , _l n' r sz b e) p pp fc s) o u .o u( ; } v rp pp a ou; s nn su (i dw ' pn ,fn to ( { i o. t bw no , oe ' uc i n ) p pp ={ ou f cs s nn sy ) ou : i o .p ( } ; r tr p pp e u n o u; }; ) a tC ml t. pn o u( za ae c m) u oo p ee oe Pp p ' e lk .o '; o (i dw oe .a l di h' el k .o ' ' b ak,' ei a l' ) k wn o .p nc le Wt ( za ae cm , _l n' rs zb e) ; o (o u. ou .a l d ' o u c a gd) k pp p fc sc le , fc s hn e';
  • 10. MOCKING CONSTRUCTORS Constructors are functions with t i being the object to construct hs t i. nu = nw wn o . u oo pe ei pt l mn ,{ h si p t e i dw At Cm l t( nu Ee et l sU l ti .p in . it r i t r: hs o to sl sU l }; ) t i. nu .o u ( ; h si p tf cs ) s nn su (i dw ' uo o pe e, fn to ( { i o. t bw no , At Cm lt ' u ci n ) t i. ou = sn ns y ) h s fc s i o. p( ; }; ) o (o m 'r ae '; k fr , ce td ) e ul wn o. uo o pe ec lC u t 1; q a( i dw At Cm lt . al on , ) v ra g =w no .u oo p ee fr ta lc l .r s a rs i dw A tC ml t. i sC l. al ag ; o (r s0. s 'n m ') k ag []i(# ae ); d eE ul ag [ ] { it r :' sm Ul }; e pq a (r s1 , ls Ul / o er ') v ra tC ml t =w no . uo op ee fr t al cl .h s au ; a u o op ee id wA tC m lt .i sC l. a lt iV le o (u oo pe ef c sc le ) k at C ml t. ou .a l d;
  • 11. HOW TO AVOID WAITING? We want the tests to be fast So don't use Jasmine w i s o ( atFr) But we often need to wait For animations to complete For AJAX responses to return d ly ie f nt o ( { e aH d : u ci n ) v rs l =t i; a ef hs s ti eu (u c in( { e T mo tf nt o ) s l. lm n .i e) ef ee et hd ( ; } t i. pi n. ie e a) , h so to s hd Dl y; }
  • 12. MOCKING TIMERS Use Sinon's mock clock Tick the clock explicitly Now the test completes in milliseconds without waiting s nn ue ae ie s ) i o. s Fk Tm r( ; a tC ml t. ea H d( ; u oo p ee dl yi e) o (( #a e) i (: ii l' ) k $ ' n m' .s 'v sb e ); s nn co kt c( 0 ) i o. l c. ik 50 ; o (( #a e) i (: id n) ; k $ ' n m' .s 'h de ' )
  • 13. MOCKING TIME n w D t ( tends to return different values over time e ae) ...actually, that's the whole point :) But how do we test code that relies on that? We cannot e u l a value that changes on every run q a on Instead, Sinon can mock the D t ( constructor! ae) s nn ue ae ie s ) i o. s Fk Tm r( ; v rt e =n wD t( ; a hn e ae) s nn co kt c( 2 0) i o. l c. ik 40 0; v rl tr = n wD t (; a ae e ae ) e ul lt rg ti e )- te .e T m( ,4 00; q a( a e. eT m( h ng ti e) 2 0)
  • 14. MOCKING AJAX REQUESTS To test in isolation To vastly speed up the tests Many options can.fixture Mockjax Sinon c nf xu e' gt a e' f nt o (r gn l rs od ih { a .i t r( /e Nm s, u ci n oi ia , ep n Wt ) r so di h{ i t [ r ce '} ; e p nW t( ls : 'a hl ] ) }; ) v ra tC ml t = n wA t Cm lt (# ae , { a u o op ee e uo op e e' nm ' l sU l 'g ta e' i t r: /e N ms }; ) s nn co kt c( a .i tr .e a ) i o. l c. ik cn fx u ed ly ; r so di h5 0; / It r a s r e e rr e pn W t( 0) / n en l ev r ro
  • 15. DOM FIXTURES Supply the markup required by the code Automatically cleanup markup after every test Built into QUnit as #qunit-fixture $ 'i pt i=nm " '. pe do ' qn tf xu e) ( <n u d "a e >)a p nT (# ui -i t r' ; a tC ml t =n wA tC m lt (# ae ) u oo p ee e uo op ee ' nm ';
  • 16. SPYING ON EVENTS How do we test that an event was cancelled? Spy on the preventDefault() method ' ep es :f nt o (l m n, ee t { k yr s ' uc in e ee t v n) v rp te n= t i. lm n. a ( + a at r h se e etvl ) Sr n .r mh ro ee e tc aC d) t ig fo Ca C d( vn .h r oe ; v rm th= t i.e Mt hp t en ; a ac hsgt a c( at r) i(a c) { f m th e et pe e te al (; vn .r vn Df u t) t i . l m n .a ( a c ) hs ee etvl m th ; } } v rk yr sE et = $ E et 'e p es ,{ hr oe 1 9) a e p es vn . v n (k yr s' c a Cd : 0} ; s nn sy ky rs E et ' rv nD fu t) i o. p (e pe sv n, p ee t ea l' ; $'n m' .r ge ( ep es vn ) (#a e )t ig rk yr s Ee t; o (e pe sv n. r vn Df ut c le ) k ky r sE et pe et e al .a ld ;
  • 18. PARAMERIZED AND CONDITIONED TESTS Some code is browser specific maybe using a browser specific API and might only be testable in that browser Tests can be conditioned Or iterated... c ne c( a .a h [ { ec ' uc s' r so s: { it [x ] ,e pc e: [ x] , d s : s ce s , e p ne l s: ' '} x e td ' '} { ec ' al r' r so s: 5 0 e pc e :[ } d s : f iu e, e p ne 0 , xe td ] ] fn t o ( cn r o { , u ci n se ai ) t s(ls Ul o to ,' +s e ai .e c fn to ( { e t'i tr p in cn ro ds , uc i n ) c nf xu e 'g ta e' f nt o (r gn l rs o di h { a. it r( /e N ms , uc in o ii a, e pn Wt ) r so d ih se ai . ep ne ; ep nW t( c nr or so s) }; ) d eE ul a tC ml t. p in .i t se ai .x e td ; ep qa (u oo p ee ot os ls , cn r oe pc e) }; ) }; )
  • 20. DOM ELEMENT LEAKS DOM Fixtures are cleaned up automatically But sometimes code needs to go beyond the fixture, appending to $('body'), e.g for overlays That code should have a way to clean up those elements And our tests should invoke that cleanup And we can easily verify that this is always done t ad w: fn to ( { e ro n u ci n ) v rl as =$ ' oy )c id e (: o( qn tr p re ) ) a ek (b d' . hl rn 'n t# u i- eo tr ' ; e ul la sl n t, 0 'o DM ee et l ae ' ; q a (e k. eg h , n O l mn s ek d ) l as rm v( ; e k .e oe ) }
  • 21. MEMORY LEAKS window.performance.memory: a Google Chrome extension run Chrome with --enable-memory-info --js-flags="--exposegc" Collect memory consumption data for every test Sort and investigate the largest memory consumers However, performance data is not reproducible And the garbage collector disturbs the picture But still usable s tp f nt o ( { e u: u ci n ) w no .c ) i d wg (; t i. ep ie e oe =w no. ef ra c. eo y ue JH aS z; h s ha Sz Bf r i d wp r o m n e m m r. s d S e p i e } , t ad w: fn to ( { e ro n u ci n ) w no .c ) i d wg (; t i. ep ie f e = w no.e fr ac . eo yu eJ H aS z; h s ha Sz At r i dwp ro mn em mr . sd Se pi e c no el gs e.e pi ef e -s e . e pi ee oe; o s l. o( pcha S zA tr pc ha Sz B fr) }