SlideShare ist ein Scribd-Unternehmen logo
1 von 34
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

CI CD Pipeline Using Jenkins | Continuous Integration and Deployment | DevOps...
CI CD Pipeline Using Jenkins | Continuous Integration and Deployment | DevOps...CI CD Pipeline Using Jenkins | Continuous Integration and Deployment | DevOps...
CI CD Pipeline Using Jenkins | Continuous Integration and Deployment | DevOps...Edureka!
 
How to go about testing in React?
How to go about testing in React? How to go about testing in React?
How to go about testing in React? Lisa Gagarina
 
Cypress - Best Practices
Cypress - Best PracticesCypress - Best Practices
Cypress - Best PracticesBrian Mann
 
Scrum Testing Methodology
Scrum Testing MethodologyScrum Testing Methodology
Scrum Testing MethodologyGaya1985
 
Cypress e2e automation testing - day1 intor by: Hassan Hameed
Cypress e2e automation testing -  day1 intor by: Hassan HameedCypress e2e automation testing -  day1 intor by: Hassan Hameed
Cypress e2e automation testing - day1 intor by: Hassan HameedHassan Muhammad
 
Introduction to jenkins
Introduction to jenkinsIntroduction to jenkins
Introduction to jenkinsAbe Diaz
 
Maven 3 Overview
Maven 3  OverviewMaven 3  Overview
Maven 3 OverviewMike Ensor
 
Selenium Tutorial For Beginners | Selenium Automation Testing Tutorial | Sele...
Selenium Tutorial For Beginners | Selenium Automation Testing Tutorial | Sele...Selenium Tutorial For Beginners | Selenium Automation Testing Tutorial | Sele...
Selenium Tutorial For Beginners | Selenium Automation Testing Tutorial | Sele...Simplilearn
 
Introduction to E2E in Cypress
Introduction to E2E in CypressIntroduction to E2E in Cypress
Introduction to E2E in CypressFabio Biondi
 
Selenium WebDriver Tutorial | Selenium WebDriver Tutorial For Beginner | Sele...
Selenium WebDriver Tutorial | Selenium WebDriver Tutorial For Beginner | Sele...Selenium WebDriver Tutorial | Selenium WebDriver Tutorial For Beginner | Sele...
Selenium WebDriver Tutorial | Selenium WebDriver Tutorial For Beginner | Sele...Simplilearn
 
Introduction to Jira - Bug Tracking tool
Introduction to Jira - Bug Tracking toolIntroduction to Jira - Bug Tracking tool
Introduction to Jira - Bug Tracking toolGlobal SQA
 
RESTful API Testing using Postman, Newman, and Jenkins
RESTful API Testing using Postman, Newman, and JenkinsRESTful API Testing using Postman, Newman, and Jenkins
RESTful API Testing using Postman, Newman, and JenkinsQASymphony
 
Testing in Agile Projects
Testing in Agile ProjectsTesting in Agile Projects
Testing in Agile Projectssriks7
 
An Introduction To Jenkins
An Introduction To JenkinsAn Introduction To Jenkins
An Introduction To JenkinsKnoldus Inc.
 

Was ist angesagt? (20)

CI CD Pipeline Using Jenkins | Continuous Integration and Deployment | DevOps...
CI CD Pipeline Using Jenkins | Continuous Integration and Deployment | DevOps...CI CD Pipeline Using Jenkins | Continuous Integration and Deployment | DevOps...
CI CD Pipeline Using Jenkins | Continuous Integration and Deployment | DevOps...
 
How to go about testing in React?
How to go about testing in React? How to go about testing in React?
How to go about testing in React?
 
Cypress - Best Practices
Cypress - Best PracticesCypress - Best Practices
Cypress - Best Practices
 
Scrum Testing Methodology
Scrum Testing MethodologyScrum Testing Methodology
Scrum Testing Methodology
 
Cypress e2e automation testing - day1 intor by: Hassan Hameed
Cypress e2e automation testing -  day1 intor by: Hassan HameedCypress e2e automation testing -  day1 intor by: Hassan Hameed
Cypress e2e automation testing - day1 intor by: Hassan Hameed
 
Jenkins
JenkinsJenkins
Jenkins
 
Introduction to jenkins
Introduction to jenkinsIntroduction to jenkins
Introduction to jenkins
 
Cypress testing
Cypress testingCypress testing
Cypress testing
 
Maven 3 Overview
Maven 3  OverviewMaven 3  Overview
Maven 3 Overview
 
Selenium Tutorial For Beginners | Selenium Automation Testing Tutorial | Sele...
Selenium Tutorial For Beginners | Selenium Automation Testing Tutorial | Sele...Selenium Tutorial For Beginners | Selenium Automation Testing Tutorial | Sele...
Selenium Tutorial For Beginners | Selenium Automation Testing Tutorial | Sele...
 
Introduction to E2E in Cypress
Introduction to E2E in CypressIntroduction to E2E in Cypress
Introduction to E2E in Cypress
 
Maven ppt
Maven pptMaven ppt
Maven ppt
 
Selenium WebDriver Tutorial | Selenium WebDriver Tutorial For Beginner | Sele...
Selenium WebDriver Tutorial | Selenium WebDriver Tutorial For Beginner | Sele...Selenium WebDriver Tutorial | Selenium WebDriver Tutorial For Beginner | Sele...
Selenium WebDriver Tutorial | Selenium WebDriver Tutorial For Beginner | Sele...
 
BDD with Cucumber
BDD with CucumberBDD with Cucumber
BDD with Cucumber
 
Maven
MavenMaven
Maven
 
Introduction to Jira - Bug Tracking tool
Introduction to Jira - Bug Tracking toolIntroduction to Jira - Bug Tracking tool
Introduction to Jira - Bug Tracking tool
 
RESTful API Testing using Postman, Newman, and Jenkins
RESTful API Testing using Postman, Newman, and JenkinsRESTful API Testing using Postman, Newman, and Jenkins
RESTful API Testing using Postman, Newman, and Jenkins
 
Feature toggles
Feature togglesFeature toggles
Feature toggles
 
Testing in Agile Projects
Testing in Agile ProjectsTesting in Agile Projects
Testing in Agile Projects
 
An Introduction To Jenkins
An Introduction To JenkinsAn Introduction To Jenkins
An Introduction To Jenkins
 

Andere mochten auch

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
 
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
 

Andere mochten auch (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
 
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...
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Mehr von Christopher Bartling

Mehr von 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
 

Kürzlich hochgeladen

Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
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
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
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
 
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
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
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
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 

Kürzlich hochgeladen (20)

Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
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
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
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
 
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
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
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
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 

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