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

AV Evasion with the Veil Framework
AV Evasion with the Veil FrameworkAV Evasion with the Veil Framework
AV Evasion with the Veil FrameworkVeilFramework
 
Mockito a simple, intuitive mocking framework
Mockito   a simple, intuitive mocking frameworkMockito   a simple, intuitive mocking framework
Mockito a simple, intuitive mocking frameworkPhat VU
 
Understanding Unit Testing
Understanding Unit TestingUnderstanding Unit Testing
Understanding Unit Testingikhwanhayat
 
Selenium Grid
Selenium GridSelenium Grid
Selenium Gridnirvdrum
 
Intro to Pentesting Jenkins
Intro to Pentesting JenkinsIntro to Pentesting Jenkins
Intro to Pentesting JenkinsBrian Hysell
 
elasticsearch_적용 및 활용_정리
elasticsearch_적용 및 활용_정리elasticsearch_적용 및 활용_정리
elasticsearch_적용 및 활용_정리Junyi Song
 
파이썬 생존 안내서 (자막)
파이썬 생존 안내서 (자막)파이썬 생존 안내서 (자막)
파이썬 생존 안내서 (자막)Heungsub Lee
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practicesnickokiss
 
JPA and Hibernate Performance Tips
JPA and Hibernate Performance TipsJPA and Hibernate Performance Tips
JPA and Hibernate Performance TipsVlad Mihalcea
 
Static Code Analysis
Static Code AnalysisStatic Code Analysis
Static Code AnalysisAnnyce Davis
 
AI 연구자를 위한 클린코드 - GDG DevFest Seoul 2019
AI 연구자를 위한 클린코드 - GDG DevFest Seoul 2019AI 연구자를 위한 클린코드 - GDG DevFest Seoul 2019
AI 연구자를 위한 클린코드 - GDG DevFest Seoul 2019Kenneth Ceyer
 
POST/CON 2019 Workshop: Testing, Automated Testing, and Reporting APIs with P...
POST/CON 2019 Workshop: Testing, Automated Testing, and Reporting APIs with P...POST/CON 2019 Workshop: Testing, Automated Testing, and Reporting APIs with P...
POST/CON 2019 Workshop: Testing, Automated Testing, and Reporting APIs with P...Postman
 
Why TypeScript?
Why TypeScript?Why TypeScript?
Why TypeScript?FITC
 
Java Basics for selenium
Java Basics for seleniumJava Basics for selenium
Java Basics for seleniumapoorvams
 

What's hot (20)

AV Evasion with the Veil Framework
AV Evasion with the Veil FrameworkAV Evasion with the Veil Framework
AV Evasion with the Veil Framework
 
Angular Unit Testing
Angular Unit TestingAngular Unit Testing
Angular Unit Testing
 
Mockito a simple, intuitive mocking framework
Mockito   a simple, intuitive mocking frameworkMockito   a simple, intuitive mocking framework
Mockito a simple, intuitive mocking framework
 
JMockit
JMockitJMockit
JMockit
 
Belajar Postman test runner
Belajar Postman test runnerBelajar Postman test runner
Belajar Postman test runner
 
Understanding Unit Testing
Understanding Unit TestingUnderstanding Unit Testing
Understanding Unit Testing
 
Selenium Grid
Selenium GridSelenium Grid
Selenium Grid
 
Intro to Pentesting Jenkins
Intro to Pentesting JenkinsIntro to Pentesting Jenkins
Intro to Pentesting Jenkins
 
elasticsearch_적용 및 활용_정리
elasticsearch_적용 및 활용_정리elasticsearch_적용 및 활용_정리
elasticsearch_적용 및 활용_정리
 
파이썬 생존 안내서 (자막)
파이썬 생존 안내서 (자막)파이썬 생존 안내서 (자막)
파이썬 생존 안내서 (자막)
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practices
 
JPA and Hibernate Performance Tips
JPA and Hibernate Performance TipsJPA and Hibernate Performance Tips
JPA and Hibernate Performance Tips
 
Static Code Analysis
Static Code AnalysisStatic Code Analysis
Static Code Analysis
 
Workshop unit test
Workshop   unit testWorkshop   unit test
Workshop unit test
 
AI 연구자를 위한 클린코드 - GDG DevFest Seoul 2019
AI 연구자를 위한 클린코드 - GDG DevFest Seoul 2019AI 연구자를 위한 클린코드 - GDG DevFest Seoul 2019
AI 연구자를 위한 클린코드 - GDG DevFest Seoul 2019
 
SonarQube
SonarQubeSonarQube
SonarQube
 
POST/CON 2019 Workshop: Testing, Automated Testing, and Reporting APIs with P...
POST/CON 2019 Workshop: Testing, Automated Testing, and Reporting APIs with P...POST/CON 2019 Workshop: Testing, Automated Testing, and Reporting APIs with P...
POST/CON 2019 Workshop: Testing, Automated Testing, and Reporting APIs with P...
 
Jenkins CI presentation
Jenkins CI presentationJenkins CI presentation
Jenkins CI presentation
 
Why TypeScript?
Why TypeScript?Why TypeScript?
Why TypeScript?
 
Java Basics for selenium
Java Basics for seleniumJava Basics for selenium
Java Basics for selenium
 

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
 
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
 
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
 
Professionelle Anforderungsanalyse am Beispiel einer Java-Anwendung zur Betri...
Professionelle Anforderungsanalyse am Beispiel einer Java-Anwendung zur Betri...Professionelle Anforderungsanalyse am Beispiel einer Java-Anwendung zur Betri...
Professionelle Anforderungsanalyse am Beispiel einer Java-Anwendung zur Betri...GFU Cyrus AG
 
Javascript pour le développeur Java
Javascript pour le développeur JavaJavascript pour le développeur Java
Javascript pour le développeur Javajollivetc
 

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
 
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
 
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
 
Professionelle Anforderungsanalyse am Beispiel einer Java-Anwendung zur Betri...
Professionelle Anforderungsanalyse am Beispiel einer Java-Anwendung zur Betri...Professionelle Anforderungsanalyse am Beispiel einer Java-Anwendung zur Betri...
Professionelle Anforderungsanalyse am Beispiel einer Java-Anwendung zur Betri...
 
Javascript pour le développeur Java
Javascript pour le développeur JavaJavascript pour le développeur Java
Javascript pour le développeur Java
 

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

Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 

Recently uploaded (20)

Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 

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