SlideShare une entreprise Scribd logo
1  sur  36
Télécharger pour lire hors ligne
Automated Jasmine Tests for
JavaScript
Hazem Saleh
About Me
- Ten years of experience in Java enterprise, portal, and mobile
solutions.
- Apache Committer and an open source guy.
- Author of three books
- Author of many articles about web development best practices.
- DeveloperWorks Contributing author.
- Technical Speaker (JavaOne, ApacheCon, JSFDays, Confess,
JDC ...etc)
- Advisory Software Engineer in IBM.
O
U
T
L
I
N
E
JavaScript Testing Challenges
Picking your JS Unit Testing framework
Jasmine Overview
Asynchronous Jasmine Tests
Weather Application Tests Demo
Automating Jasmine Tests using Karma JS (Demo)
Jasmine Code Coverage using Karma JS (Demo)
Conclusion
Integrating Jasmine tests with Build and CI tools (two Demos)
JavaScript Testing Challenges
Requires a lot of time to test on all the browsers.
JavaScript code that works on a browser X does not mean that it will work on browser Y.
Supporting a new browser on an existing system means allocating a new budget:
For testing this system on this browser.
For fixing newly discovered defects on this browser.
O
U
T
L
I
N
E
JavaScript Testing Challenges
Picking your JS Unit Testing framework
Jasmine Overview
Asynchronous Jasmine Tests
Weather Application Tests Demo
Automating Jasmine Tests using Karma JS (Demo)
Jasmine Code Coverage using Karma JS (Demo)
Conclusion
Integrating Jasmine tests with Build and CI tools (two Demos)
Picking your JS Unit Testing framework
JavaScript unit testing
tool
Executable across
browsers (Automated
preferred)
Easy to setup
Easy to configure
Fast Execution
Integrated
Provides a good testing
mechanism for
Asynchronous code
O
U
T
L
I
N
E
JavaScript Testing Challenges
Picking your JS Unit Testing framework
Jasmine Overview
Asynchronous Jasmine Tests
Weather Application Tests Demo
Automating Jasmine Tests using Karma JS (Demo)
Jasmine Code Coverage using Karma JS (Demo)
Conclusion
Integrating Jasmine tests with Build and CI tools (two Demos)
Jasmine Overview
Jasmine is a powerful JavaScript unit testing framework.
Jasmine describes its tests in a simple natural language.
Jasmine tests can be read by Non-programmers.
Jasmine provides a clean mechanism for testing synchronous and asynchronous
code.
Jasmine Overview
Sample Jasmine Test:
describe("A sample suite", function() {
it("contains a spec with an expectation", function() {
expect(true).toEqual(true);
});
});
Main Jasmine Constructs:
TestSuite begins with a call to describe().
TestCase “or spec” begins with a call to it().
TestCase can contain one or more matcher(s).
Jasmine Overview
Jasmine Main Matchers:
expect(x).toEqual(y) expect(x).toBe[Un]Defined()
expect(x).toBeNull()
expect(x).toBeTruthy()
expect(x).toBeFalsy()
expect(x).toContain(y)expect(x).toBeLessThan(y)
expect(x).toBeGreaterThan(y)
expect(x).toMatch(pattern)
expect(x).toWhatEver(Y)
“custom matcher”
Jasmine Overview
beforeEach and afterEach example:
describe("SimpleMath", function() {
var simpleMath;
beforeEach(function() {
simpleMath = new SimpleMath();
});
it("should be able to find factorial for positive number", function() {
expect(simpleMath.getFactorial(3)).toEqual(6);
});
it("should be able to find factorial for zero", function() {
expect(simpleMath.getFactorial(0)).toEqual(1);
});
afterEach(function() {
simpleMath = null;
});
});
Jasmine Overview
Jasmine First Test Demo
O
U
T
L
I
N
E
JavaScript Testing Challenges
Picking your JS Unit Testing framework
Jasmine Overview
Asynchronous Jasmine Tests
Weather Application Tests Demo
Automating Jasmine Tests using Karma JS (Demo)
Jasmine Code Coverage using Karma JS (Demo)
Conclusion
Integrating Jasmine tests with Build and CI tools (two Demos)
Asynchronous Jasmine Tests
Asynchronous JavaScript code refers to the code whose caller will NOT to wait
until the execution completes.
In order to get the results, the caller should pass callbacks which will be called
with data results parameters in case of operation success or failure.
Asynchronous JavaScript code mainly refers to Ajax code.
In order to support Asynchronous operation testing, Jasmine provides:
1. An optional single parameter for its single spec.
2. This parameter has to be called if the asynchronous operation completes.
3. If this parameter is not called for by default 5 seconds then the test will fail
(means operation timeout).
Asynchronous Jasmine Tests
describe("when doing asynchronous operation", function() {
it("should be able to do the asynchronous operation", function(done) {
var data = {};
var successCallBack = function(result) {
console.log("success");
/* validate result parameter */
done();
};
var failureCallBack = function() {
console.log("failure");
expect("Operation").toBe("passing"); /* force failing test */
done();
};
AsyncObject.asyncOperation(data, successCallBack, failureCallBack);
});
});
Testing an Async Operation
Loading Jasmine Fixtures
Fixture module of jasmine-jquery (use jQuery core) allows loading the HTML
content to be used by the tests.
Put the fixtures you want to load for your tests in the specjavascriptsfixtures
directory.
beforeEach(function() {
loadFixtures("registrationFixture.html");
});
(or)
beforeEach(function() {
jasmine.getFixtures().set('<div id="weatherInformation"
class="weatherPanel"></div>');
});
O
U
T
L
I
N
E
JavaScript Testing Challenges
Picking your JS Unit Testing framework
Jasmine Overview
Asynchronous Jasmine Tests
Weather Application Tests Demo
Automating Jasmine Tests using Karma JS (Demo)
Jasmine Code Coverage using Karma JS (Demo)
Conclusion
Integrating Jasmine tests with Build and CI tools (two Demos)
Weather Application Tests Demo
Weather Application Test Demo:
1. Loading Fixtures example.
2. Performing asynchronous operation testing example.
O
U
T
L
I
N
E
JavaScript Testing Challenges
Picking your JS Unit Testing framework
Jasmine Overview
Asynchronous Jasmine Tests
Weather Application Tests Demo
Automating Jasmine Tests using Karma JS (Demo)
Jasmine Code Coverage using Karma JS (Demo)
Conclusion
Integrating Jasmine tests with Build and CI tools (two Demos)
Automating Jasmine Tests using Karma JS
Jasmine is very cool and powerful JavaScript Unit Testing framework.
However, Jasmine is designed to work from browsers.
In order to automate Jasmine tests, we need to use a JavaScript test runner.
You have two great options from many options:
JsTestDriver Karma JS
Automating Jasmine Tests using Karma JS
Karma JS is a modern JavaScript test runner that can be used for automating
JavaScript tests.
Karma JS is designed to bring a productive test environment for web developers.
It is based on Node JS and is distributed as a node package.
It provides an easy-to-use command line interface.
Automating Jasmine Tests using Karma JS
In order to use Karma JS:
Install Karma JS:
npm install karma
Jasmine QUnit
Generate your test
configuration file:
karma init config.js
Start your Karma
server:
karma start config.js
Fortunately, Karma JS supports popular testing frameworks, some of
them are:
Automating Jasmine Tests using Karma JS
Sample Karma JS Jasmine configuration file:
module.exports = function(config) {
config.set({
frameworks: ['jasmine'], /* Used testing frameworks */
files: [ 'js-test/jasmine/lib/plugins/jasmine-jquery/jquery.js',
'js-test/jasmine/lib/plugins/jasmine-jquery/jasmine-jquery.js',
'js-src/*.js', 'js-test/jasmine/spec/*.js'], /* Files to be loaded in the browser */
reporters: ['progress'],
port: 9876,
autoWatch: true, /* Execute tests when a file changes */
browsers: ['Chrome'], /* Captured startup browsers */
});
};
Automating Jasmine Tests using Karma JS
By Default, Karma ONLY outputs the tests results on the console.
In order to output the test results in JUnit XML format, we need to install karma-
junit-reporter plugin.
npm install karma-junit-reporter --save-dev
Add JUnit reporter parameters to your configuration.
In order to include JUnit reporter plugin to your project:
Automating Jasmine Tests using Karma JS
module.exports = function(config) {
config.set({
//...
reporters: ['progress', 'junit'],
// Generate test results in this file
junitReporter: {
outputFile: 'test-results.xml'
}
});
};
Demo
1. Automating running Jasmine tests in Karma.
2. Exploring Karma's JUnit XML results.
O
U
T
L
I
N
E
JavaScript Testing Challenges
Picking your JS Unit Testing framework
Jasmine Overview
Asynchronous Jasmine Tests
Weather Application Tests Demo
Automating Jasmine Tests using Karma JS (Demo)
Jasmine Code Coverage using Karma JS (Demo)
Conclusion
Integrating Jasmine tests with Build and CI tools (two Demos)
Jasmine Code Coverage using Karma JS
Karma JS code coverage can be performed using Istanbul module.
Istanbul supports:
Line coverage
In order to include Istanbul in your test project:
Function coverage Branch coverage
npm install karma-coverage --save-dev
Add Istanbul parameters to your configuration.
Jasmine Code Coverage using Karma JS
module.exports = function(config) {
config.set({
//...
reporters: ['progress', 'coverage'],
preprocessors: {
// src files to generate coverage for
'src/*.js': ['coverage']
},
// The reporter configuration
coverageReporter: {
type : 'html',
dir : 'coverage/'
}
});
};
Demo
Generating Code Coverage Reports
O
U
T
L
I
N
E
JavaScript Testing Challenges
Picking your JS Unit Testing framework
Jasmine Overview
Asynchronous Jasmine Tests
Weather Application Tests Demo
Automating Jasmine Tests using Karma JS (Demo)
Jasmine Code Coverage using Karma JS (Demo)
Conclusion
Integrating Jasmine tests with Build and CI tools (two Demos)
Demo
Integrating tests with Build and Integration
Management tools
O
U
T
L
I
N
E
JavaScript Testing Challenges
Picking your JS Unit Testing framework
Jasmine Overview
Asynchronous Jasmine Tests
Weather Application Tests Demo
Automating Jasmine Tests using Karma JS (Demo)
Jasmine Code Coverage using Karma JS (Demo)
Conclusion
Integrating Jasmine tests with Build and CI tools (two Demos)
Conclusion
Jasmine is a powerful unit testing framework that allows you to develop read-
able maintainable JavaScript tests.
Karma JS is a modern Node JS test runner which allows automating JavaScript
tests.
Thanks to Karma JS, we can now have automated Jasmine tests.
Thanks to Karma JS and Jasmine, testing JavaScript code becomes
fun :).
JavaScript Quiz
<script>
var number = 50;
var obj = {
number: 60,
getNum: function () {
var number = 70;
return this.number;
}
};
alert(obj.getNum());
alert(obj.getNum.call());
alert(obj.getNum.call({number:20}));
</script>
Questions/Contact me
Twitter: @hazems
Email: hazems@apache.org
Example Demo project source code is available in GitHub:
https://github.com/hazems/JsUnitTesting

Contenu connexe

En vedette

AngularJS Unit Test
AngularJS Unit TestAngularJS Unit Test
AngularJS Unit TestChiew Carol
 
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]
 
Intro to testing Javascript with jasmine
Intro to testing Javascript with jasmineIntro to testing Javascript with jasmine
Intro to testing Javascript with jasmineTimothy Oxley
 
Unit testing in JavaScript with Jasmine and Karma
Unit testing in JavaScript with Jasmine and KarmaUnit testing in JavaScript with Jasmine and Karma
Unit testing in JavaScript with Jasmine and KarmaAndrey Kolodnitsky
 
Angularjs - Unit testing introduction
Angularjs - Unit testing introductionAngularjs - Unit testing introduction
Angularjs - Unit testing introductionNir Kaufman
 
JavaScript TDD with Jasmine and Karma
JavaScript TDD with Jasmine and KarmaJavaScript TDD with Jasmine and Karma
JavaScript TDD with Jasmine and KarmaChristopher 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
 
Javascript Tests with Jasmine for Front-end Devs
Javascript Tests with Jasmine for Front-end DevsJavascript Tests with Jasmine for Front-end Devs
Javascript Tests with Jasmine for Front-end DevsChris Powers
 
AngularJS Unit Testing w/Karma and Jasmine
AngularJS Unit Testing w/Karma and JasmineAngularJS Unit Testing w/Karma and Jasmine
AngularJS Unit Testing w/Karma and Jasminefoxp2code
 

En vedette (13)

Angular testing
Angular testingAngular testing
Angular testing
 
AngularJS Unit Test
AngularJS Unit TestAngularJS Unit Test
AngularJS Unit Test
 
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
 
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
 
Intro to testing Javascript with jasmine
Intro to testing Javascript with jasmineIntro to testing Javascript with jasmine
Intro to testing Javascript with jasmine
 
Unit testing in JavaScript with Jasmine and Karma
Unit testing in JavaScript with Jasmine and KarmaUnit testing in JavaScript with Jasmine and Karma
Unit testing in JavaScript with Jasmine and Karma
 
Angularjs - Unit testing introduction
Angularjs - Unit testing introductionAngularjs - Unit testing introduction
Angularjs - Unit testing introduction
 
JavaScript TDD with Jasmine and Karma
JavaScript TDD with Jasmine and KarmaJavaScript TDD with Jasmine and Karma
JavaScript TDD with Jasmine 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
 
Javascript Tests with Jasmine for Front-end Devs
Javascript Tests with Jasmine for Front-end DevsJavascript Tests with Jasmine for Front-end Devs
Javascript Tests with Jasmine for Front-end Devs
 
Jasmine
JasmineJasmine
Jasmine
 
AngularJS Unit Testing w/Karma and Jasmine
AngularJS Unit Testing w/Karma and JasmineAngularJS Unit Testing w/Karma and Jasmine
AngularJS Unit Testing w/Karma and Jasmine
 

Plus de Hazem Saleh

[FullStack NYC 2019] Effective Unit Tests for JavaScript
[FullStack NYC 2019] Effective Unit Tests for JavaScript[FullStack NYC 2019] Effective Unit Tests for JavaScript
[FullStack NYC 2019] Effective Unit Tests for JavaScriptHazem Saleh
 
Mockito 2.x Migration - Droidcon UK 2018
Mockito 2.x Migration - Droidcon UK 2018Mockito 2.x Migration - Droidcon UK 2018
Mockito 2.x Migration - Droidcon UK 2018Hazem Saleh
 
JavaScript Unit Testing with an Angular 5.x Use Case 101
JavaScript Unit Testing with an Angular 5.x Use Case 101JavaScript Unit Testing with an Angular 5.x Use Case 101
JavaScript Unit Testing with an Angular 5.x Use Case 101Hazem Saleh
 
[AnDevCon 2016] Mutation Testing for Android
[AnDevCon 2016] Mutation Testing for Android[AnDevCon 2016] Mutation Testing for Android
[AnDevCon 2016] Mutation Testing for AndroidHazem Saleh
 
[ApacheCon 2016] Advanced Apache Cordova
[ApacheCon 2016] Advanced Apache Cordova[ApacheCon 2016] Advanced Apache Cordova
[ApacheCon 2016] Advanced Apache CordovaHazem Saleh
 
[Devoxx Morocco 2015] Apache Cordova In Action
[Devoxx Morocco 2015] Apache Cordova In Action[Devoxx Morocco 2015] Apache Cordova In Action
[Devoxx Morocco 2015] Apache Cordova In ActionHazem Saleh
 
Apache Cordova In Action
Apache Cordova In ActionApache Cordova In Action
Apache Cordova In ActionHazem Saleh
 
[JavaLand 2015] Developing JavaScript Mobile Apps Using Apache Cordova
[JavaLand 2015] Developing JavaScript Mobile Apps Using Apache Cordova[JavaLand 2015] Developing JavaScript Mobile Apps Using Apache Cordova
[JavaLand 2015] Developing JavaScript Mobile Apps Using Apache CordovaHazem Saleh
 
[JMaghreb 2014] Developing JavaScript Mobile Apps Using Apache Cordova
[JMaghreb 2014] Developing JavaScript Mobile Apps Using Apache Cordova[JMaghreb 2014] Developing JavaScript Mobile Apps Using Apache Cordova
[JMaghreb 2014] Developing JavaScript Mobile Apps Using Apache CordovaHazem Saleh
 
Developing Native Mobile Apps Using JavaScript, ApacheCon NA 2014
Developing Native Mobile Apps Using JavaScript, ApacheCon NA 2014Developing Native Mobile Apps Using JavaScript, ApacheCon NA 2014
Developing Native Mobile Apps Using JavaScript, ApacheCon NA 2014Hazem Saleh
 
Dojo >= 1.7 Kickstart
Dojo >= 1.7  KickstartDojo >= 1.7  Kickstart
Dojo >= 1.7 KickstartHazem Saleh
 
Efficient JavaScript Unit Testing (Chinese Version), JavaOne China 2013
Efficient JavaScript Unit Testing (Chinese Version), JavaOne China 2013Efficient JavaScript Unit Testing (Chinese Version), JavaOne China 2013
Efficient JavaScript Unit Testing (Chinese Version), JavaOne China 2013Hazem Saleh
 
Efficient JavaScript Unit Testing, JavaOne China 2013
Efficient JavaScript Unit Testing, JavaOne China 2013Efficient JavaScript Unit Testing, JavaOne China 2013
Efficient JavaScript Unit Testing, JavaOne China 2013Hazem Saleh
 
JSF Mashups in Action
JSF Mashups in ActionJSF Mashups in Action
JSF Mashups in ActionHazem Saleh
 
Efficient JavaScript Unit Testing, March 2013
Efficient JavaScript Unit Testing, March 2013Efficient JavaScript Unit Testing, March 2013
Efficient JavaScript Unit Testing, March 2013Hazem Saleh
 
JavaScript tools
JavaScript toolsJavaScript tools
JavaScript toolsHazem Saleh
 
Efficient JavaScript Unit Testing, May 2012
Efficient JavaScript Unit Testing, May 2012Efficient JavaScript Unit Testing, May 2012
Efficient JavaScript Unit Testing, May 2012Hazem Saleh
 
[JavaOne 2010] Abstract Mashups for Enterprise Java
[JavaOne 2010] Abstract Mashups for Enterprise Java[JavaOne 2010] Abstract Mashups for Enterprise Java
[JavaOne 2010] Abstract Mashups for Enterprise JavaHazem Saleh
 

Plus de Hazem Saleh (19)

[FullStack NYC 2019] Effective Unit Tests for JavaScript
[FullStack NYC 2019] Effective Unit Tests for JavaScript[FullStack NYC 2019] Effective Unit Tests for JavaScript
[FullStack NYC 2019] Effective Unit Tests for JavaScript
 
Mockito 2.x Migration - Droidcon UK 2018
Mockito 2.x Migration - Droidcon UK 2018Mockito 2.x Migration - Droidcon UK 2018
Mockito 2.x Migration - Droidcon UK 2018
 
JavaScript Unit Testing with an Angular 5.x Use Case 101
JavaScript Unit Testing with an Angular 5.x Use Case 101JavaScript Unit Testing with an Angular 5.x Use Case 101
JavaScript Unit Testing with an Angular 5.x Use Case 101
 
[AnDevCon 2016] Mutation Testing for Android
[AnDevCon 2016] Mutation Testing for Android[AnDevCon 2016] Mutation Testing for Android
[AnDevCon 2016] Mutation Testing for Android
 
[ApacheCon 2016] Advanced Apache Cordova
[ApacheCon 2016] Advanced Apache Cordova[ApacheCon 2016] Advanced Apache Cordova
[ApacheCon 2016] Advanced Apache Cordova
 
[Devoxx Morocco 2015] Apache Cordova In Action
[Devoxx Morocco 2015] Apache Cordova In Action[Devoxx Morocco 2015] Apache Cordova In Action
[Devoxx Morocco 2015] Apache Cordova In Action
 
Apache Cordova In Action
Apache Cordova In ActionApache Cordova In Action
Apache Cordova In Action
 
[JavaLand 2015] Developing JavaScript Mobile Apps Using Apache Cordova
[JavaLand 2015] Developing JavaScript Mobile Apps Using Apache Cordova[JavaLand 2015] Developing JavaScript Mobile Apps Using Apache Cordova
[JavaLand 2015] Developing JavaScript Mobile Apps Using Apache Cordova
 
[JMaghreb 2014] Developing JavaScript Mobile Apps Using Apache Cordova
[JMaghreb 2014] Developing JavaScript Mobile Apps Using Apache Cordova[JMaghreb 2014] Developing JavaScript Mobile Apps Using Apache Cordova
[JMaghreb 2014] Developing JavaScript Mobile Apps Using Apache Cordova
 
Developing Native Mobile Apps Using JavaScript, ApacheCon NA 2014
Developing Native Mobile Apps Using JavaScript, ApacheCon NA 2014Developing Native Mobile Apps Using JavaScript, ApacheCon NA 2014
Developing Native Mobile Apps Using JavaScript, ApacheCon NA 2014
 
Dojo >= 1.7 Kickstart
Dojo >= 1.7  KickstartDojo >= 1.7  Kickstart
Dojo >= 1.7 Kickstart
 
Efficient JavaScript Unit Testing (Chinese Version), JavaOne China 2013
Efficient JavaScript Unit Testing (Chinese Version), JavaOne China 2013Efficient JavaScript Unit Testing (Chinese Version), JavaOne China 2013
Efficient JavaScript Unit Testing (Chinese Version), JavaOne China 2013
 
Efficient JavaScript Unit Testing, JavaOne China 2013
Efficient JavaScript Unit Testing, JavaOne China 2013Efficient JavaScript Unit Testing, JavaOne China 2013
Efficient JavaScript Unit Testing, JavaOne China 2013
 
JSF Mashups in Action
JSF Mashups in ActionJSF Mashups in Action
JSF Mashups in Action
 
Efficient JavaScript Unit Testing, March 2013
Efficient JavaScript Unit Testing, March 2013Efficient JavaScript Unit Testing, March 2013
Efficient JavaScript Unit Testing, March 2013
 
JavaScript tools
JavaScript toolsJavaScript tools
JavaScript tools
 
Efficient JavaScript Unit Testing, May 2012
Efficient JavaScript Unit Testing, May 2012Efficient JavaScript Unit Testing, May 2012
Efficient JavaScript Unit Testing, May 2012
 
[JavaOne 2010] Abstract Mashups for Enterprise Java
[JavaOne 2010] Abstract Mashups for Enterprise Java[JavaOne 2010] Abstract Mashups for Enterprise Java
[JavaOne 2010] Abstract Mashups for Enterprise Java
 
GMaps4JSF
GMaps4JSFGMaps4JSF
GMaps4JSF
 

Dernier

FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseAnaAcapella
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxcallscotland1987
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdfssuserdda66b
 

Dernier (20)

FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
 

Automated Jasmine Tests for JavaScript, Geecon 2014

  • 1. Automated Jasmine Tests for JavaScript Hazem Saleh
  • 2. About Me - Ten years of experience in Java enterprise, portal, and mobile solutions. - Apache Committer and an open source guy. - Author of three books - Author of many articles about web development best practices. - DeveloperWorks Contributing author. - Technical Speaker (JavaOne, ApacheCon, JSFDays, Confess, JDC ...etc) - Advisory Software Engineer in IBM.
  • 3. O U T L I N E JavaScript Testing Challenges Picking your JS Unit Testing framework Jasmine Overview Asynchronous Jasmine Tests Weather Application Tests Demo Automating Jasmine Tests using Karma JS (Demo) Jasmine Code Coverage using Karma JS (Demo) Conclusion Integrating Jasmine tests with Build and CI tools (two Demos)
  • 4. JavaScript Testing Challenges Requires a lot of time to test on all the browsers. JavaScript code that works on a browser X does not mean that it will work on browser Y. Supporting a new browser on an existing system means allocating a new budget: For testing this system on this browser. For fixing newly discovered defects on this browser.
  • 5. O U T L I N E JavaScript Testing Challenges Picking your JS Unit Testing framework Jasmine Overview Asynchronous Jasmine Tests Weather Application Tests Demo Automating Jasmine Tests using Karma JS (Demo) Jasmine Code Coverage using Karma JS (Demo) Conclusion Integrating Jasmine tests with Build and CI tools (two Demos)
  • 6. Picking your JS Unit Testing framework JavaScript unit testing tool Executable across browsers (Automated preferred) Easy to setup Easy to configure Fast Execution Integrated Provides a good testing mechanism for Asynchronous code
  • 7. O U T L I N E JavaScript Testing Challenges Picking your JS Unit Testing framework Jasmine Overview Asynchronous Jasmine Tests Weather Application Tests Demo Automating Jasmine Tests using Karma JS (Demo) Jasmine Code Coverage using Karma JS (Demo) Conclusion Integrating Jasmine tests with Build and CI tools (two Demos)
  • 8. Jasmine Overview Jasmine is a powerful JavaScript unit testing framework. Jasmine describes its tests in a simple natural language. Jasmine tests can be read by Non-programmers. Jasmine provides a clean mechanism for testing synchronous and asynchronous code.
  • 9. Jasmine Overview Sample Jasmine Test: describe("A sample suite", function() { it("contains a spec with an expectation", function() { expect(true).toEqual(true); }); }); Main Jasmine Constructs: TestSuite begins with a call to describe(). TestCase “or spec” begins with a call to it(). TestCase can contain one or more matcher(s).
  • 10. Jasmine Overview Jasmine Main Matchers: expect(x).toEqual(y) expect(x).toBe[Un]Defined() expect(x).toBeNull() expect(x).toBeTruthy() expect(x).toBeFalsy() expect(x).toContain(y)expect(x).toBeLessThan(y) expect(x).toBeGreaterThan(y) expect(x).toMatch(pattern) expect(x).toWhatEver(Y) “custom matcher”
  • 11. Jasmine Overview beforeEach and afterEach example: describe("SimpleMath", function() { var simpleMath; beforeEach(function() { simpleMath = new SimpleMath(); }); it("should be able to find factorial for positive number", function() { expect(simpleMath.getFactorial(3)).toEqual(6); }); it("should be able to find factorial for zero", function() { expect(simpleMath.getFactorial(0)).toEqual(1); }); afterEach(function() { simpleMath = null; }); });
  • 13. O U T L I N E JavaScript Testing Challenges Picking your JS Unit Testing framework Jasmine Overview Asynchronous Jasmine Tests Weather Application Tests Demo Automating Jasmine Tests using Karma JS (Demo) Jasmine Code Coverage using Karma JS (Demo) Conclusion Integrating Jasmine tests with Build and CI tools (two Demos)
  • 14. Asynchronous Jasmine Tests Asynchronous JavaScript code refers to the code whose caller will NOT to wait until the execution completes. In order to get the results, the caller should pass callbacks which will be called with data results parameters in case of operation success or failure. Asynchronous JavaScript code mainly refers to Ajax code. In order to support Asynchronous operation testing, Jasmine provides: 1. An optional single parameter for its single spec. 2. This parameter has to be called if the asynchronous operation completes. 3. If this parameter is not called for by default 5 seconds then the test will fail (means operation timeout).
  • 15. Asynchronous Jasmine Tests describe("when doing asynchronous operation", function() { it("should be able to do the asynchronous operation", function(done) { var data = {}; var successCallBack = function(result) { console.log("success"); /* validate result parameter */ done(); }; var failureCallBack = function() { console.log("failure"); expect("Operation").toBe("passing"); /* force failing test */ done(); }; AsyncObject.asyncOperation(data, successCallBack, failureCallBack); }); }); Testing an Async Operation
  • 16. Loading Jasmine Fixtures Fixture module of jasmine-jquery (use jQuery core) allows loading the HTML content to be used by the tests. Put the fixtures you want to load for your tests in the specjavascriptsfixtures directory. beforeEach(function() { loadFixtures("registrationFixture.html"); }); (or) beforeEach(function() { jasmine.getFixtures().set('<div id="weatherInformation" class="weatherPanel"></div>'); });
  • 17. O U T L I N E JavaScript Testing Challenges Picking your JS Unit Testing framework Jasmine Overview Asynchronous Jasmine Tests Weather Application Tests Demo Automating Jasmine Tests using Karma JS (Demo) Jasmine Code Coverage using Karma JS (Demo) Conclusion Integrating Jasmine tests with Build and CI tools (two Demos)
  • 18. Weather Application Tests Demo Weather Application Test Demo: 1. Loading Fixtures example. 2. Performing asynchronous operation testing example.
  • 19. O U T L I N E JavaScript Testing Challenges Picking your JS Unit Testing framework Jasmine Overview Asynchronous Jasmine Tests Weather Application Tests Demo Automating Jasmine Tests using Karma JS (Demo) Jasmine Code Coverage using Karma JS (Demo) Conclusion Integrating Jasmine tests with Build and CI tools (two Demos)
  • 20. Automating Jasmine Tests using Karma JS Jasmine is very cool and powerful JavaScript Unit Testing framework. However, Jasmine is designed to work from browsers. In order to automate Jasmine tests, we need to use a JavaScript test runner. You have two great options from many options: JsTestDriver Karma JS
  • 21. Automating Jasmine Tests using Karma JS Karma JS is a modern JavaScript test runner that can be used for automating JavaScript tests. Karma JS is designed to bring a productive test environment for web developers. It is based on Node JS and is distributed as a node package. It provides an easy-to-use command line interface.
  • 22. Automating Jasmine Tests using Karma JS In order to use Karma JS: Install Karma JS: npm install karma Jasmine QUnit Generate your test configuration file: karma init config.js Start your Karma server: karma start config.js Fortunately, Karma JS supports popular testing frameworks, some of them are:
  • 23. Automating Jasmine Tests using Karma JS Sample Karma JS Jasmine configuration file: module.exports = function(config) { config.set({ frameworks: ['jasmine'], /* Used testing frameworks */ files: [ 'js-test/jasmine/lib/plugins/jasmine-jquery/jquery.js', 'js-test/jasmine/lib/plugins/jasmine-jquery/jasmine-jquery.js', 'js-src/*.js', 'js-test/jasmine/spec/*.js'], /* Files to be loaded in the browser */ reporters: ['progress'], port: 9876, autoWatch: true, /* Execute tests when a file changes */ browsers: ['Chrome'], /* Captured startup browsers */ }); };
  • 24. Automating Jasmine Tests using Karma JS By Default, Karma ONLY outputs the tests results on the console. In order to output the test results in JUnit XML format, we need to install karma- junit-reporter plugin. npm install karma-junit-reporter --save-dev Add JUnit reporter parameters to your configuration. In order to include JUnit reporter plugin to your project:
  • 25. Automating Jasmine Tests using Karma JS module.exports = function(config) { config.set({ //... reporters: ['progress', 'junit'], // Generate test results in this file junitReporter: { outputFile: 'test-results.xml' } }); };
  • 26. Demo 1. Automating running Jasmine tests in Karma. 2. Exploring Karma's JUnit XML results.
  • 27. O U T L I N E JavaScript Testing Challenges Picking your JS Unit Testing framework Jasmine Overview Asynchronous Jasmine Tests Weather Application Tests Demo Automating Jasmine Tests using Karma JS (Demo) Jasmine Code Coverage using Karma JS (Demo) Conclusion Integrating Jasmine tests with Build and CI tools (two Demos)
  • 28. Jasmine Code Coverage using Karma JS Karma JS code coverage can be performed using Istanbul module. Istanbul supports: Line coverage In order to include Istanbul in your test project: Function coverage Branch coverage npm install karma-coverage --save-dev Add Istanbul parameters to your configuration.
  • 29. Jasmine Code Coverage using Karma JS module.exports = function(config) { config.set({ //... reporters: ['progress', 'coverage'], preprocessors: { // src files to generate coverage for 'src/*.js': ['coverage'] }, // The reporter configuration coverageReporter: { type : 'html', dir : 'coverage/' } }); };
  • 31. O U T L I N E JavaScript Testing Challenges Picking your JS Unit Testing framework Jasmine Overview Asynchronous Jasmine Tests Weather Application Tests Demo Automating Jasmine Tests using Karma JS (Demo) Jasmine Code Coverage using Karma JS (Demo) Conclusion Integrating Jasmine tests with Build and CI tools (two Demos)
  • 32. Demo Integrating tests with Build and Integration Management tools
  • 33. O U T L I N E JavaScript Testing Challenges Picking your JS Unit Testing framework Jasmine Overview Asynchronous Jasmine Tests Weather Application Tests Demo Automating Jasmine Tests using Karma JS (Demo) Jasmine Code Coverage using Karma JS (Demo) Conclusion Integrating Jasmine tests with Build and CI tools (two Demos)
  • 34. Conclusion Jasmine is a powerful unit testing framework that allows you to develop read- able maintainable JavaScript tests. Karma JS is a modern Node JS test runner which allows automating JavaScript tests. Thanks to Karma JS, we can now have automated Jasmine tests. Thanks to Karma JS and Jasmine, testing JavaScript code becomes fun :).
  • 35. JavaScript Quiz <script> var number = 50; var obj = { number: 60, getNum: function () { var number = 70; return this.number; } }; alert(obj.getNum()); alert(obj.getNum.call()); alert(obj.getNum.call({number:20})); </script>
  • 36. Questions/Contact me Twitter: @hazems Email: hazems@apache.org Example Demo project source code is available in GitHub: https://github.com/hazems/JsUnitTesting