SlideShare a Scribd company logo
1 of 34
Download to read offline
JavaScript Test-Driven Development
with Jasmine and Karma
!
!
!
!
!
!
!
!
Christopher Bartling
1
Justifying test-driven JavaScript development
• JavaScript is a first-class citizen in our products.
• Modern web applications are predominantly written in
JavaScript with some markup.
• JavaScript usage is growing, even on the server-side.
• Production quality code should be tested.
• Unit, integration, and functional/acceptance testing.
• Don’t practice reckless development!
2
Quick review of test-driven development
• Use unit tests to drive development and design.
• Write the test first, then the code.
• See the test fail, then make it pass.
• Importance of spiking before test-first development.
• Test coverage of your code remains high because of test-
first approach.
• A fast test suite is typically run frequently.
3
Benefits of test-driven development
• Design tool.
• Helps build confidence.
• Executable documentation of the code base.
• Tests infer the intent of the code.
• Code base is continually executed when test suites are
run in continuous integration environments.
• Avoid code rot.
4
The test-driven development cadence
Start with a failing
test
Write code to make
the test pass
Refactor code
and tests
5
The importance of “spiking”
• Test-driven development is grounded in the assumption
that you know your tools and what you are building.
• When unsure about how the solution should proceed,
use spike solutions to learn more about what you’re
attempting to do.
• Spike solutions are not production code.
• Spike solutions are typically thrown away. Value is in the
problem domain learning that takes place.
6
karma
• JavaScript test runner that integrates with a number of
browser runners.
• Dependent on node.js, distributed as a node package.
• Command line tool, but also integrated into JetBrains
WebStorm IDE.
➜ calculator git:(master) ✗ karma start

INFO [karma]: Karma v0.10.8 server started at http://localhost:9876/

INFO [launcher]: Starting browser PhantomJS

INFO [PhantomJS 1.9.2 (Mac OS X)]: Connected on socket TbzZHmxXJQ3aKLGcIIel

PhantomJS 1.9.2 (Mac OS X): Executed 12 of 12 SUCCESS (0.022 secs / 0.003 secs)
7
phantom.js
• Headless WebKit browser runner, scriptable with a
JavaScript API
• Native support for various web standards
• DOM, Canvas, and SVG
• CSS selectors
• JSON
8
Introducing Jasmine
• Testing framework
• Suites possess a hierarchical structure
• Tests as specifications
• Matchers, both built-in and custom
• Spies, a test double pattern
9
Jasmine suite
describe("A specification suite", function() {



	 … 



});	
• Group specifications together using nested describe
function blocks.
• Also useful for delineating context-specific specifications.
10
Jasmine specification
describe("A specification suite", function() {



	 it(“contains spec with an expectation", function() {

	 	 expect(view.tagName).toBe(‘tr’);

	 });



});	
• Specifications are expressed with the it function.
• The description should read well in the report.
• Expectations are expressed with the expect function.
11
Jasmine matchers
12
• not	
• toBe	
• toEqual	
• toMatch	
• toBeDefined	
• toBeUndefined	
• toBeNull
• toBeTruthy	
• toBeFalsy	
• toContain	
• toBeLessThan	
• toBeGreaterThan	
• toBeCloseTo	
• toThrow
Jasmine setup using beforeEach
describe("PintailConsulting.ToDoListView", function() {

	 var view;



	 beforeEach(function(){

	 	 view = new PintailConsulting.ToDoListView();

	 });



	 it(“sets the tagName to ‘div’", function() {

	 	 expect(view.tagName).toBe(‘div’);

	 });

});
13
Jasmine tear down using afterEach
describe("PintailConsulting.ToDoListView", function() {

	 var view;



	 beforeEach(function(){

	 	 view = new PintailConsulting.ToDoListView();

	 });



	 afterEach(function(){

	 	 view = null;

	 });



	 it(“sets the tagName to ‘div’", function() {

	 	 expect(view.tagName).toBe(‘div’);

	 });

});
14
Jasmine custom matchers
beforeEach(function() { 

	 this.addMatchers({

	 	 toBeLessThan: function(expected) {

	 	 	 var actual = this.actual;

	 	 	 var notText = this.isNot ? " not" : "";



	 	 	 this.message = function () {

	 	 	 	 return "Expected " + actual + notText + 

	 	 	 	 	 	 " to be less than " + expected;

	 	 	 }

	 	 	 return actual < expected;

	 	 }

	 });

});
15
Demonstration
16
Jasmine spies
• Test double pattern.
• Interception-based test double mechanism provided by
the Jasmine library.
• Spies record invocations and invocation parameters,
allowing you to inspect the spy after exercising the SUT.
• Very similar to mock objects.
• More information at https://github.com/pivotal/jasmine/
wiki/Spies.
17
Jasmine spy usage
Spying and verifying invocation
var spy = spyOn(dependency, “render”);

systemUnderTest.display();

expect(spy).toHaveBeenCalled();	


Spying, verifying invocation and argument(s)
var spy = spyOn(dependency, “render”);

systemUnderTest.display(“Hello”);

expect(spy).toHaveBeenCalledWith(“Hello”);
18
Jasmine spy usage
Spying, verifying number of invocations and arguments for
each call
var spy = spyOn(Leaflet, “circle”).andCallThrough();

mapView.processResults(earthquakeJsonResults);

expect(spy).toHaveBeenCalled()

expect(circleConstructorSpy.callCount).toBe(2);

expect(circleConstructorSpy.argsForCall[0][0])

.toEqual([56.6812, -155.0237])
19
Loose matching with jasmine.any
• Accepts a constructor or “class” name as an expected
value.
• Returns true if the constructor matches the constructor
of the actual value.


var spy = jasmine.createSpy(My.Namespace, ’foo’);

foo(12, function(x) { return x * x; });
expect(spy).toHaveBeenCalledWith

	 (jasmine.any(Number), jasmine.any(Function));
20
Jasmine spy usage
• andCallThrough(): Allows the invocation to passthrough
to the real subject.
• andReturn(result): Return a hard-coded result.
• andCallFake(fakeImplFunction): Return a
dynamically generated result from a function.
• createSpy(identity): Manually create a spy.
• createSpyObj(identity, propertiesArray):
Creates a mock with multiple property spies.
21
Jasmine asynchronous support
• Use runs and waitsFor blocks and a latch function.
• The latch function polls until it returns true or the timeout
expires, whichever comes first.
• If the timeout expires, the specification fails with a
message.
• Kind of clunky to use.
22
Jasmine asynchronous example
describe("an async spec", function() { 

	 var done;



	 beforeEach(function() {

	 	 done = false;

	 	 var doStuff = function() {

	 	 	 // simulate async stuff and wait 10ms

	 	 	 setTimeout(function() { done = true; }, 10); 

	 	 };

	 	 runs(doStuff);

	 	 waitsFor(function() { return done; }, 

	 	 	 ‘The doStuff function should be done by now.’, 

	 	 	 100); 

	 });



	 it("did stuff", function() {

	 	 expect(done).toBe(true);

	 });

});
23
karma-coverage
• Test coverage plugin for karma
• https://github.com/karma-runner/karma-coverage
npm install karma-coverage --save-dev	
• Run karma with coverage configured (karma.conf.js)
• Generate reports using istanbul report
• Reports saved to the coverage subdirectory
24
Code coverage report
25
Unit testing tips
• Strive for one assertion per example.
• Allows all assertions to execute.
• Each assertion runs in a clean SUT setup.
• Avoid making live AJAX calls in your unit tests/specs.
• Spy/intercept the low-level AJAX invocations
(jQuery.ajax)
• Use fixture data for testing AJAX callbacks.
26
How do we sustain test-driven development?
• Practice, practice, practice!
• Code katas,
• Pair programming, even in remote situations.
• Screenhero, Hangouts, Skype
• Continuous integration server.
• Run your test suites often, preferably on every commit.
27
Functional/acceptance testing
• Very important part of the testing portfolio.
• Many tools support testing web-based user interfaces
today.
• Geb, Capybara, Cucumber{Ruby|jvm|js}, Protractor.js,
Concordian, spock
• You should strongly consider adding functional/
acceptance testing in your testing portfolio.
• Covers areas of code that unit testing cannot cover.
28
Tool references
• http://phantomjs.org
• http://karma-runner.github.io/
• http://gruntjs.com/
• http://bower.io/
• http://pivotal.github.io/jasmine/
• http://yeoman.io/
29
Recommended reading
• Secrets of the JavaScript Ninja - John Resig and Bear
Bibeault
• JavaScript: The Good Parts - Douglas Crockford
• Test-Driven JavaScript Development - Christian
Johansen
30
Learning resources
• Let’s Code: Test-Driven JavaScript
• http://www.letscodejavascript.com/
• Egghead.io
• http://egghead.io/
31
Code kata resources
• http://katas.softwarecraftsmanship.org/
• http://codekata.pragprog.com/
• http://projecteuler.net/
• http://codekatas.org/
32
Presentation GitHub repository
• https://github.com/cebartling/ncaa-basketball-
tournament
• The web-client directory contains this entire sample
Backbone.js-based application.
33
Thank you!
• Christopher Bartling
• @cbartling
• chris@pintailconsultingllc.com
34

More Related Content

What's hot (20)

Unit tests & TDD
Unit tests & TDDUnit tests & TDD
Unit tests & TDD
 
Learning typescript
Learning typescriptLearning typescript
Learning typescript
 
Saving Time By Testing With Jest
Saving Time By Testing With JestSaving Time By Testing With Jest
Saving Time By Testing With Jest
 
Junit
JunitJunit
Junit
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Angular & RXJS: examples and use cases
Angular & RXJS: examples and use casesAngular & RXJS: examples and use cases
Angular & RXJS: examples and use cases
 
Performance testing methodologies
Performance testing methodologiesPerformance testing methodologies
Performance testing methodologies
 
PUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootPUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBoot
 
Typescript Fundamentals
Typescript FundamentalsTypescript Fundamentals
Typescript Fundamentals
 
Jenkins presentation
Jenkins presentationJenkins presentation
Jenkins presentation
 
JavaFX Presentation
JavaFX PresentationJavaFX Presentation
JavaFX Presentation
 
TypeScript intro
TypeScript introTypeScript intro
TypeScript intro
 
TypeScript Overview
TypeScript OverviewTypeScript Overview
TypeScript Overview
 
Karate, the black belt of HTTP API testing?
Karate, the black belt of HTTP API testing?Karate, the black belt of HTTP API testing?
Karate, the black belt of HTTP API testing?
 
Continuous integration
Continuous integrationContinuous integration
Continuous integration
 
Testing of React JS app
Testing of React JS appTesting of React JS app
Testing of React JS app
 
Introduction to ASP.NET Core
Introduction to ASP.NET CoreIntroduction to ASP.NET Core
Introduction to ASP.NET Core
 
Getting started with typescript
Getting started with typescriptGetting started with typescript
Getting started with typescript
 
Protocol Buffers
Protocol BuffersProtocol Buffers
Protocol Buffers
 
Linq to sql
Linq to sqlLinq to sql
Linq to sql
 

Viewers also liked

Intro to testing Javascript with jasmine
Intro to testing Javascript with jasmineIntro to testing Javascript with jasmine
Intro to testing Javascript with jasmineTimothy Oxley
 
Angularjs - Unit testing introduction
Angularjs - Unit testing introductionAngularjs - Unit testing introduction
Angularjs - Unit testing introductionNir Kaufman
 
Linux Performance Tools
Linux Performance ToolsLinux Performance Tools
Linux Performance ToolsBrendan Gregg
 
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 TestingLars Thorup
 
Bdd 개요 및 Karma 도입 예
Bdd 개요 및 Karma 도입 예Bdd 개요 및 Karma 도입 예
Bdd 개요 및 Karma 도입 예Seulgi Choi
 
jQuery 3 main changes
jQuery 3 main changesjQuery 3 main changes
jQuery 3 main changesOsama Quboh
 
TDD, unit testing and java script testing frameworks workshop
TDD, unit testing and java script testing frameworks workshopTDD, unit testing and java script testing frameworks workshop
TDD, unit testing and java script testing frameworks workshopSikandar Ahmed
 
Angular 2 - What's new and what's different
Angular 2 - What's new and what's differentAngular 2 - What's new and what's different
Angular 2 - What's new and what's differentPriscila Negreiros
 
Unit testing JavaScript: Jasmine & karma intro
Unit testing JavaScript: Jasmine & karma introUnit testing JavaScript: Jasmine & karma intro
Unit testing JavaScript: Jasmine & karma introMaurice De Beijer [MVP]
 
AngularJS Unit Test
AngularJS Unit TestAngularJS Unit Test
AngularJS Unit TestChiew Carol
 
Jasmine - A BDD test framework for JavaScript
Jasmine - A BDD test framework for JavaScriptJasmine - A BDD test framework for JavaScript
Jasmine - A BDD test framework for JavaScriptSumanth krishna
 
JavaScript Test-Driven Development with Jasmine 2.0 and Karma
JavaScript Test-Driven Development with Jasmine 2.0 and Karma JavaScript Test-Driven Development with Jasmine 2.0 and Karma
JavaScript Test-Driven Development with Jasmine 2.0 and Karma Christopher Bartling
 
Automated Testing With Jasmine, PhantomJS and Jenkins
Automated Testing With Jasmine, PhantomJS and JenkinsAutomated Testing With Jasmine, PhantomJS and Jenkins
Automated Testing With Jasmine, PhantomJS and JenkinsWork at Play
 
Inclure du Javascript de manière performante
Inclure du Javascript de manière performanteInclure du Javascript de manière performante
Inclure du Javascript de manière performanteJean-Pierre Vincent
 
Borang data murid
Borang data muridBorang data murid
Borang data muridJasmine Eng
 

Viewers also liked (20)

Karma - JS Test Runner
Karma - JS Test RunnerKarma - JS Test Runner
Karma - JS Test Runner
 
Intro to testing Javascript with jasmine
Intro to testing Javascript with jasmineIntro to testing Javascript with jasmine
Intro to testing Javascript with jasmine
 
Angularjs - Unit testing introduction
Angularjs - Unit testing introductionAngularjs - Unit testing introduction
Angularjs - Unit testing introduction
 
TDD Basics with Angular.js and Jasmine
TDD Basics with Angular.js and JasmineTDD Basics with Angular.js and Jasmine
TDD Basics with Angular.js and Jasmine
 
Linux Performance Tools
Linux Performance ToolsLinux Performance Tools
Linux Performance Tools
 
Jasmine
JasmineJasmine
Jasmine
 
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
 
Bdd 개요 및 Karma 도입 예
Bdd 개요 및 Karma 도입 예Bdd 개요 및 Karma 도입 예
Bdd 개요 및 Karma 도입 예
 
Jquery 3
Jquery 3Jquery 3
Jquery 3
 
jQuery 3 main changes
jQuery 3 main changesjQuery 3 main changes
jQuery 3 main changes
 
TDD, unit testing and java script testing frameworks workshop
TDD, unit testing and java script testing frameworks workshopTDD, unit testing and java script testing frameworks workshop
TDD, unit testing and java script testing frameworks workshop
 
Angular testing
Angular testingAngular testing
Angular testing
 
Angular 2 - What's new and what's different
Angular 2 - What's new and what's differentAngular 2 - What's new and what's different
Angular 2 - What's new and what's different
 
Unit testing JavaScript: Jasmine & karma intro
Unit testing JavaScript: Jasmine & karma introUnit testing JavaScript: Jasmine & karma intro
Unit testing JavaScript: Jasmine & karma intro
 
AngularJS Unit Test
AngularJS Unit TestAngularJS Unit Test
AngularJS Unit Test
 
Jasmine - A BDD test framework for JavaScript
Jasmine - A BDD test framework for JavaScriptJasmine - A BDD test framework for JavaScript
Jasmine - A BDD test framework for JavaScript
 
JavaScript Test-Driven Development with Jasmine 2.0 and Karma
JavaScript Test-Driven Development with Jasmine 2.0 and Karma JavaScript Test-Driven Development with Jasmine 2.0 and Karma
JavaScript Test-Driven Development with Jasmine 2.0 and Karma
 
Automated Testing With Jasmine, PhantomJS and Jenkins
Automated Testing With Jasmine, PhantomJS and JenkinsAutomated Testing With Jasmine, PhantomJS and Jenkins
Automated Testing With Jasmine, PhantomJS and Jenkins
 
Inclure du Javascript de manière performante
Inclure du Javascript de manière performanteInclure du Javascript de manière performante
Inclure du Javascript de manière performante
 
Borang data murid
Borang data muridBorang data murid
Borang data murid
 

Similar to JavaScript TDD with Jasmine and Karma

Quick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmineQuick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmineGil Fink
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.jsorkaplan
 
Testing Ext JS and Sencha Touch
Testing Ext JS and Sencha TouchTesting Ext JS and Sencha Touch
Testing Ext JS and Sencha TouchMats Bryntse
 
Quick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmineQuick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmineGil Fink
 
CBDW2014 - MockBox, get ready to mock your socks off!
CBDW2014 - MockBox, get ready to mock your socks off!CBDW2014 - MockBox, get ready to mock your socks off!
CBDW2014 - MockBox, get ready to mock your socks off!Ortus Solutions, Corp
 
Qt test framework
Qt test frameworkQt test framework
Qt test frameworkICS
 
Java script unit testing
Java script unit testingJava script unit testing
Java script unit testingMats Bryntse
 
Unit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJSUnit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJSKnoldus Inc.
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript TestingKissy Team
 
OWASP ZAP Workshop for QA Testers
OWASP ZAP Workshop for QA TestersOWASP ZAP Workshop for QA Testers
OWASP ZAP Workshop for QA TestersJavan Rasokat
 
Performance Test Driven Development with Oracle Coherence
Performance Test Driven Development with Oracle CoherencePerformance Test Driven Development with Oracle Coherence
Performance Test Driven Development with Oracle Coherencearagozin
 
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit TutorialJAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit TutorialAnup Singh
 
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...Paul King
 
[AWS Dev Day] 실습워크샵 | Amazon EKS 핸즈온 워크샵
 [AWS Dev Day] 실습워크샵 | Amazon EKS 핸즈온 워크샵 [AWS Dev Day] 실습워크샵 | Amazon EKS 핸즈온 워크샵
[AWS Dev Day] 실습워크샵 | Amazon EKS 핸즈온 워크샵Amazon Web Services Korea
 
The Many Ways to Test Your React App
The Many Ways to Test Your React AppThe Many Ways to Test Your React App
The Many Ways to Test Your React AppAll Things Open
 
Safe Wrappers and Sane Policies for Self Protecting JavaScript
Safe Wrappers and Sane Policies for Self Protecting JavaScript�Safe Wrappers and Sane Policies for Self Protecting JavaScript�
Safe Wrappers and Sane Policies for Self Protecting JavaScriptPhú Phùng
 
Jakarta EE Test Strategies (2022)
Jakarta EE Test Strategies (2022)Jakarta EE Test Strategies (2022)
Jakarta EE Test Strategies (2022)Ryan Cuprak
 
Building stable testing by isolating network layer
Building stable testing by isolating network layerBuilding stable testing by isolating network layer
Building stable testing by isolating network layerJz Chang
 

Similar to JavaScript TDD with Jasmine and Karma (20)

Quick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmineQuick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmine
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 
Testing Ext JS and Sencha Touch
Testing Ext JS and Sencha TouchTesting Ext JS and Sencha Touch
Testing Ext JS and Sencha Touch
 
Quick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmineQuick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmine
 
CBDW2014 - MockBox, get ready to mock your socks off!
CBDW2014 - MockBox, get ready to mock your socks off!CBDW2014 - MockBox, get ready to mock your socks off!
CBDW2014 - MockBox, get ready to mock your socks off!
 
Qt test framework
Qt test frameworkQt test framework
Qt test framework
 
Java script unit testing
Java script unit testingJava script unit testing
Java script unit testing
 
Unit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJSUnit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJS
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testing
 
OWASP ZAP Workshop for QA Testers
OWASP ZAP Workshop for QA TestersOWASP ZAP Workshop for QA Testers
OWASP ZAP Workshop for QA Testers
 
Performance Test Driven Development with Oracle Coherence
Performance Test Driven Development with Oracle CoherencePerformance Test Driven Development with Oracle Coherence
Performance Test Driven Development with Oracle Coherence
 
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit TutorialJAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
 
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
 
[AWS Dev Day] 실습워크샵 | Amazon EKS 핸즈온 워크샵
 [AWS Dev Day] 실습워크샵 | Amazon EKS 핸즈온 워크샵 [AWS Dev Day] 실습워크샵 | Amazon EKS 핸즈온 워크샵
[AWS Dev Day] 실습워크샵 | Amazon EKS 핸즈온 워크샵
 
Nashorn
NashornNashorn
Nashorn
 
The Many Ways to Test Your React App
The Many Ways to Test Your React AppThe Many Ways to Test Your React App
The Many Ways to Test Your React App
 
Safe Wrappers and Sane Policies for Self Protecting JavaScript
Safe Wrappers and Sane Policies for Self Protecting JavaScript�Safe Wrappers and Sane Policies for Self Protecting JavaScript�
Safe Wrappers and Sane Policies for Self Protecting JavaScript
 
Jakarta EE Test Strategies (2022)
Jakarta EE Test Strategies (2022)Jakarta EE Test Strategies (2022)
Jakarta EE Test Strategies (2022)
 
Advanced Java Testing
Advanced Java TestingAdvanced Java Testing
Advanced Java Testing
 
Building stable testing by isolating network layer
Building stable testing by isolating network layerBuilding stable testing by isolating network layer
Building stable testing by isolating network layer
 

More from Christopher Bartling

More from Christopher Bartling (11)

Acceptance Test-driven Development with Cucumber-jvm
Acceptance Test-driven Development with Cucumber-jvmAcceptance Test-driven Development with Cucumber-jvm
Acceptance Test-driven Development with Cucumber-jvm
 
Building Tropo Apps with Grails
Building Tropo Apps with GrailsBuilding Tropo Apps with Grails
Building Tropo Apps with Grails
 
CoffeeScript By Example
CoffeeScript By ExampleCoffeeScript By Example
CoffeeScript By Example
 
Acceptance Test Driven Development With Spec Flow And Friends
Acceptance Test Driven Development With Spec Flow And FriendsAcceptance Test Driven Development With Spec Flow And Friends
Acceptance Test Driven Development With Spec Flow And Friends
 
Introduction To Grails
Introduction To GrailsIntroduction To Grails
Introduction To Grails
 
Cucumber, Cuke4Duke, and Groovy
Cucumber, Cuke4Duke, and GroovyCucumber, Cuke4Duke, and Groovy
Cucumber, Cuke4Duke, and Groovy
 
Test Driven In Groovy
Test Driven In GroovyTest Driven In Groovy
Test Driven In Groovy
 
iPhone OS: The Next Killer Platform
iPhone OS: The Next Killer PlatformiPhone OS: The Next Killer Platform
iPhone OS: The Next Killer Platform
 
RESTful Web Services
RESTful Web ServicesRESTful Web Services
RESTful Web Services
 
Grails Overview
Grails OverviewGrails Overview
Grails Overview
 
Rich Web Clients 20081118
Rich Web Clients 20081118Rich Web Clients 20081118
Rich Web Clients 20081118
 

Recently uploaded

Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 

Recently uploaded (20)

Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 

JavaScript TDD with Jasmine and Karma

  • 1. JavaScript Test-Driven Development with Jasmine and Karma ! ! ! ! ! ! ! ! Christopher Bartling 1
  • 2. Justifying test-driven JavaScript development • JavaScript is a first-class citizen in our products. • Modern web applications are predominantly written in JavaScript with some markup. • JavaScript usage is growing, even on the server-side. • Production quality code should be tested. • Unit, integration, and functional/acceptance testing. • Don’t practice reckless development! 2
  • 3. Quick review of test-driven development • Use unit tests to drive development and design. • Write the test first, then the code. • See the test fail, then make it pass. • Importance of spiking before test-first development. • Test coverage of your code remains high because of test- first approach. • A fast test suite is typically run frequently. 3
  • 4. Benefits of test-driven development • Design tool. • Helps build confidence. • Executable documentation of the code base. • Tests infer the intent of the code. • Code base is continually executed when test suites are run in continuous integration environments. • Avoid code rot. 4
  • 5. The test-driven development cadence Start with a failing test Write code to make the test pass Refactor code and tests 5
  • 6. The importance of “spiking” • Test-driven development is grounded in the assumption that you know your tools and what you are building. • When unsure about how the solution should proceed, use spike solutions to learn more about what you’re attempting to do. • Spike solutions are not production code. • Spike solutions are typically thrown away. Value is in the problem domain learning that takes place. 6
  • 7. karma • JavaScript test runner that integrates with a number of browser runners. • Dependent on node.js, distributed as a node package. • Command line tool, but also integrated into JetBrains WebStorm IDE. ➜ calculator git:(master) ✗ karma start
 INFO [karma]: Karma v0.10.8 server started at http://localhost:9876/
 INFO [launcher]: Starting browser PhantomJS
 INFO [PhantomJS 1.9.2 (Mac OS X)]: Connected on socket TbzZHmxXJQ3aKLGcIIel
 PhantomJS 1.9.2 (Mac OS X): Executed 12 of 12 SUCCESS (0.022 secs / 0.003 secs) 7
  • 8. phantom.js • Headless WebKit browser runner, scriptable with a JavaScript API • Native support for various web standards • DOM, Canvas, and SVG • CSS selectors • JSON 8
  • 9. Introducing Jasmine • Testing framework • Suites possess a hierarchical structure • Tests as specifications • Matchers, both built-in and custom • Spies, a test double pattern 9
  • 10. Jasmine suite describe("A specification suite", function() {
 
 … 
 
 }); • Group specifications together using nested describe function blocks. • Also useful for delineating context-specific specifications. 10
  • 11. Jasmine specification describe("A specification suite", function() {
 
 it(“contains spec with an expectation", function() {
 expect(view.tagName).toBe(‘tr’);
 });
 
 }); • Specifications are expressed with the it function. • The description should read well in the report. • Expectations are expressed with the expect function. 11
  • 12. Jasmine matchers 12 • not • toBe • toEqual • toMatch • toBeDefined • toBeUndefined • toBeNull • toBeTruthy • toBeFalsy • toContain • toBeLessThan • toBeGreaterThan • toBeCloseTo • toThrow
  • 13. Jasmine setup using beforeEach describe("PintailConsulting.ToDoListView", function() {
 var view;
 
 beforeEach(function(){
 view = new PintailConsulting.ToDoListView();
 });
 
 it(“sets the tagName to ‘div’", function() {
 expect(view.tagName).toBe(‘div’);
 });
 }); 13
  • 14. Jasmine tear down using afterEach describe("PintailConsulting.ToDoListView", function() {
 var view;
 
 beforeEach(function(){
 view = new PintailConsulting.ToDoListView();
 });
 
 afterEach(function(){
 view = null;
 });
 
 it(“sets the tagName to ‘div’", function() {
 expect(view.tagName).toBe(‘div’);
 });
 }); 14
  • 15. Jasmine custom matchers beforeEach(function() { 
 this.addMatchers({
 toBeLessThan: function(expected) {
 var actual = this.actual;
 var notText = this.isNot ? " not" : "";
 
 this.message = function () {
 return "Expected " + actual + notText + 
 " to be less than " + expected;
 }
 return actual < expected;
 }
 });
 }); 15
  • 17. Jasmine spies • Test double pattern. • Interception-based test double mechanism provided by the Jasmine library. • Spies record invocations and invocation parameters, allowing you to inspect the spy after exercising the SUT. • Very similar to mock objects. • More information at https://github.com/pivotal/jasmine/ wiki/Spies. 17
  • 18. Jasmine spy usage Spying and verifying invocation var spy = spyOn(dependency, “render”);
 systemUnderTest.display();
 expect(spy).toHaveBeenCalled(); 
 Spying, verifying invocation and argument(s) var spy = spyOn(dependency, “render”);
 systemUnderTest.display(“Hello”);
 expect(spy).toHaveBeenCalledWith(“Hello”); 18
  • 19. Jasmine spy usage Spying, verifying number of invocations and arguments for each call var spy = spyOn(Leaflet, “circle”).andCallThrough();
 mapView.processResults(earthquakeJsonResults);
 expect(spy).toHaveBeenCalled()
 expect(circleConstructorSpy.callCount).toBe(2);
 expect(circleConstructorSpy.argsForCall[0][0])
 .toEqual([56.6812, -155.0237]) 19
  • 20. Loose matching with jasmine.any • Accepts a constructor or “class” name as an expected value. • Returns true if the constructor matches the constructor of the actual value. 
 var spy = jasmine.createSpy(My.Namespace, ’foo’);
 foo(12, function(x) { return x * x; }); expect(spy).toHaveBeenCalledWith
 (jasmine.any(Number), jasmine.any(Function)); 20
  • 21. Jasmine spy usage • andCallThrough(): Allows the invocation to passthrough to the real subject. • andReturn(result): Return a hard-coded result. • andCallFake(fakeImplFunction): Return a dynamically generated result from a function. • createSpy(identity): Manually create a spy. • createSpyObj(identity, propertiesArray): Creates a mock with multiple property spies. 21
  • 22. Jasmine asynchronous support • Use runs and waitsFor blocks and a latch function. • The latch function polls until it returns true or the timeout expires, whichever comes first. • If the timeout expires, the specification fails with a message. • Kind of clunky to use. 22
  • 23. Jasmine asynchronous example describe("an async spec", function() { 
 var done;
 
 beforeEach(function() {
 done = false;
 var doStuff = function() {
 // simulate async stuff and wait 10ms
 setTimeout(function() { done = true; }, 10); 
 };
 runs(doStuff);
 waitsFor(function() { return done; }, 
 ‘The doStuff function should be done by now.’, 
 100); 
 });
 
 it("did stuff", function() {
 expect(done).toBe(true);
 });
 }); 23
  • 24. karma-coverage • Test coverage plugin for karma • https://github.com/karma-runner/karma-coverage npm install karma-coverage --save-dev • Run karma with coverage configured (karma.conf.js) • Generate reports using istanbul report • Reports saved to the coverage subdirectory 24
  • 26. Unit testing tips • Strive for one assertion per example. • Allows all assertions to execute. • Each assertion runs in a clean SUT setup. • Avoid making live AJAX calls in your unit tests/specs. • Spy/intercept the low-level AJAX invocations (jQuery.ajax) • Use fixture data for testing AJAX callbacks. 26
  • 27. How do we sustain test-driven development? • Practice, practice, practice! • Code katas, • Pair programming, even in remote situations. • Screenhero, Hangouts, Skype • Continuous integration server. • Run your test suites often, preferably on every commit. 27
  • 28. Functional/acceptance testing • Very important part of the testing portfolio. • Many tools support testing web-based user interfaces today. • Geb, Capybara, Cucumber{Ruby|jvm|js}, Protractor.js, Concordian, spock • You should strongly consider adding functional/ acceptance testing in your testing portfolio. • Covers areas of code that unit testing cannot cover. 28
  • 29. Tool references • http://phantomjs.org • http://karma-runner.github.io/ • http://gruntjs.com/ • http://bower.io/ • http://pivotal.github.io/jasmine/ • http://yeoman.io/ 29
  • 30. Recommended reading • Secrets of the JavaScript Ninja - John Resig and Bear Bibeault • JavaScript: The Good Parts - Douglas Crockford • Test-Driven JavaScript Development - Christian Johansen 30
  • 31. Learning resources • Let’s Code: Test-Driven JavaScript • http://www.letscodejavascript.com/ • Egghead.io • http://egghead.io/ 31
  • 32. Code kata resources • http://katas.softwarecraftsmanship.org/ • http://codekata.pragprog.com/ • http://projecteuler.net/ • http://codekatas.org/ 32
  • 33. Presentation GitHub repository • https://github.com/cebartling/ncaa-basketball- tournament • The web-client directory contains this entire sample Backbone.js-based application. 33
  • 34. Thank you! • Christopher Bartling • @cbartling • chris@pintailconsultingllc.com 34