SlideShare a Scribd company logo
1 of 41
Full-stack unit-testing 
Tech talk @ Pause
Plan 
1. Overview of frameworks and libraries for testing 
2. Testing of client side web application 
a. Test runner 
b. Unit testing stack 
c. End-2-end testing 
d. Reporting 
e. Sample: angular application testing 
3. Testing of server side 
a. Mocking of data providers 
b. Fixtures 
c. Essentials of tests 
4. Pitfalls of unit testing
Overview of frameworks
Testing of client-side 
1. Test runner - runs unit tests suite in various 
browsers and write reports using different 
formats 
2. Frameworks - skeleton for unit tests suites 
3. Utils libraries - allow to write tests in more 
expressive
Test runner 
1. Dynamically generate index file using 
required libs, sources and tests 
2. Execute web server on background 
3. Run tests in different browsers 
4. Collect test results from expectations and 
asserts 
5. Format them into report
Test runner 
Test’em - simple test 
runner 
1. Framework config: 
Mocha, Jasmine 
2. Test files 
3. Serve files 
4. Browser stack config
Test runner 
Karma - advanced test 
runner 
1. Plugins 
2. Multiple report formats 
supported 
3. Various browsers 
4. Dynamic index.html 
generation
Test runner 
Essentials 
1. Synchronization between source files 
2. Integration of frameworks 
3. Debugging
Unit testing stack 
Testing framework 
API 
● TDD 
● BDD 
Main frameworks 
● Mocha 
● Jasmine 
● describe 
o skip 
o only 
● it 
● before(done) 
● after(done) 
● beforeEach 
● afterEach
Unit testing stack 
Assertion libraries 
Chai 
● Plugins 
● Supports should and 
expect style 
Should 
● expect(foo).to.deep. 
equal(someNested 
Array) 
● should.exist(foo) 
● foo.bar.should.have 
.property(‘bar’)
Unit testing stack 
Plugins for chai 
● Allows you to write 
tests in terms of 
libraries you are 
using 
● Syntactic sugar 
● Sinon.js 
● jQuery 
● Backbone 
● Q
Unit testing stack
End-2-end testing 
Protractor (previously 
angular-scenario): 
● Access to angular 
scope from view 
● Selectors for 
directives 
● Uses selenium 
● by. 
o id 
o css 
o model 
o binding 
● element 
o sendKeys 
o setPosition 
o setSize
End-2-end testing
Reporting 
● jUnit XML - Jenkins 
love it 
● Progress, Dots - for 
console lovers 
● Coverage - 
objective metrics 
● jUnit is has better 
support of Jasmine 
● Coverage settings - 
include all sources 
not tests
Reporting
Sample angular app testing 
beforeEach(inject(function ($controller, $rootScope) { 
scope = $rootScope.$new(); 
GamesCtrl = $controller('HotelsCtrl', { 
$scope: scope, Hotels: factory 
}); 
})); 
it('should set default value for orderProp', function () { 
expect(scope.orderProp).toBe('title'); 
}); 
it('should have a List of Hotels', function () { 
expect(scope.games.length).toBe(2); 
expect(scope.games[0].title).toBe('Hilton'); 
expect(scope.games[1].freeRooms).toBe(10); 
});
Testing of server side
Mocking of data providers 
Faker.js 
● id’s 
● names, emails 
● cities, locations 
● messages, sentences, paragraphs 
Sinon.js 
● Mocking API using sinon.mock(API)
Sample code 
//Hotels data 
'use strict'; 
var Faker = require('Faker'); 
function generateOne() { 
return { 
name: Faker.random.bk_noun(), 
address: Faker.Addresses.streetAddress(), 
capacity: { 
standard: Faker.helpers.randomNumber(100), 
economy: Faker.helpers.randomNumber(100), 
luxury: Faker.helpers.randomNumber(100) 
} 
}; 
} 
module.exports.generateOne = generateOne; 
module.exports.generateMany = function (count) { 
var result = []; 
for (var i = 0; i < count; i++) { 
result.push(generateOne()) 
} 
return result; 
}
Database mapping testing 
1. No need to test mongoose API 
2. Create stub data using Faker API and 
predefined JSON 
3. Insert it into DB inside before callback 
4. Run unit test suites on test data 
5. Remove data from DB inside after callback
Sample code 
var fixtures = require('fixtures.js'); 
var api = require('api/'); 
var expect = require('chai').expect; 
var COUNT = 100; 
describe('Booking API', function () { 
describe('#search', function () { 
before(function (done) { 
fixtures.prepareData('hotels', 
COUNT, done); 
}); 
it('should return all hotes if no query 
params provided', function (done) 
{api.search('hotels', function (err, 
data) { 
expect(err).to.be.null; 
expect(data).to.be.an('object'); 
expect(data.length).to.be.eql(COUNT); 
done(); 
…. 
after(function (done) { 
fixtures.destroyData('hotels');
Alternatives 
● https://github.com/petejkim/factory-lady 
● http://chaijs.com/plugins/chai-factories 
● https://www.npmjs.com/package/rosie
Fixtures 
Rules 
1. Do not hardcode the id’s and data that is 
generated by database 
2. Put all domain specific data into fixtures, 
group them by collections 
3. Do not put null to client API object. Use 
dummy object instead.
Sample code 
// Fixtures 
var async = require('async'); 
var hotelsData = require('./hotelsData'); 
var Hotel = require('./hotelModel'); 
module.exports.prepareData = function (name, count, cb) { 
if (name !== 'hotels') { cb(new Error('Invalid data type')); return; } 
async.forEach(hotelsData.generateMany(count), function (item, callback) { 
var hotel = Hotel.createNew(item); 
hotel.save(callback); 
}, cb) 
}
Sample code 
var client = null; 
function notInitializedThrow () {throw new Error 
('Client not initialized')}; 
module.exports.init = function (config, cb) { 
if (client === null) { 
client = API.createClient(config); 
// doing some initializations tuff 
client.on('error', cb); 
client.on('connected', cb.bind(this, null)); 
} 
} 
module.exports.getClient = function () { 
if (client === null) { 
return { 
method1: notInitializedThrow, 
method2: notInitializedThrow 
} 
} else { 
return client; 
} 
}
Essentials 
1. Test should not depend on each others 
results 
2. They should not use shared data (only in 
read only mode) 
3. Do not allow skipped tests in releases 
4. Tests are not just for make it green
Integration tests 
1. They are checking of how modules are 
working together 
2. Ideal for checking of entity lifecycle - 
creation, linking to others, api calls, 
querying, destroying 
3. Execution environment should be 
configurable
References 
Tools: 
● WS: 
o WebSocket API client 
● HTTP: 
o Nock 
Article: 
● https://davidbeath.com/posts/testing-http-responses-in-nodejs. 
html
Stack 
1. Mocha as core framework 
2. Chai / Expect as assertions 
3. Request.js for HTTP requests 
4. node-websocket as ws client 
5. Faker or factory-lady for generation of test 
data
Best 
1. To put grunt test or test command as git 
merge to master hook 
2. To put shortcut for testing into npm test 
assuming that grunt is not globally installed 
3. JSHint/JSLint as pre commit hook
Worst 
1. To mix TDD and BDD 
a. TDD: Suite, test, step, setup, done 
b. BDD: Expectations, asserts 
2. To spaghetti the dependencies inside test 
code
Sample code 
describe('API method', function () { 
var temporaryData = null; 
it('should do one thing', function (done) { 
var result = API.call('somemethod'); 
temporaryData = API.call('anotherMethod'); 
expect(result).to.have.keys(['code', 'details', 'message']); 
}); 
it('should do another thing', function (done) { 
API.call('setup', temporaryData); 
var result = API.call('anotherMethod'); 
expect(result).to.be.null;
Pitfalls 
1. Separated environment for integration testing, unit 
testing development and production 
2. Do not rely on synchronous operations especially when 
they are not (callbacks, initialization process) 
3. Extra console.log’s are breaking unit test reportings
Sample code 
describe('Service API', function () { 
before(function (done) { 
thirdparty1.init(/*callback?*/); 
thirdparty2.init(/*callback?*/); 
thirdparty3.init(/*callback?*/); 
done(); 
}); 
before(function (done) { 
thirdparty1.done(/*callback?*/); 
thirdparty2.done(/*callback?*/); 
thirdparty3.done(/*callback?*/); 
done(); 
}); 
}); 
describe('Service API', function () { 
before(function (done) { 
async.waterfall([ 
thirdparty1.init, 
thirdparty2.init, 
thirdparty3.init 
], done); 
}); 
before(function (done) { 
async.waterfall([ 
thirdparty1.done, 
thirdparty2.done, 
thirdparty3.done 
], done); 
}); 
});
References 
Books 
1. Testable Javascript book 
2. JavaScript Allongé 
3. Testing with CoffeeScript 
Articles/Blogs: 
1. Full spectrum testing with angular.js and Karma 
2. Cross-browser testing on multiple devices 
3. Mocha + CoffeeScript tutorial 
4. http://code.tutsplus.com/tutorials/testing-in-nodejs--net-35018
Tools 
1. Node version manager 
2. Mocha 
3. Jasmine 
4. Karma 
5. Istanbul 
6. Protractor 
7. Selenium
QA

More Related Content

What's hot

What's hot (20)

Jasmine - why JS tests don't smell fishy
Jasmine - why JS tests don't smell fishyJasmine - why JS tests don't smell fishy
Jasmine - why JS tests don't smell fishy
 
Unit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJSUnit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJS
 
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
 
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
 
Test-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS ApplicationsTest-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS Applications
 
Testing Javascript with Jasmine
Testing Javascript with JasmineTesting Javascript with Jasmine
Testing Javascript with 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
 
Celery
CeleryCelery
Celery
 
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
 
Practical Celery
Practical CeleryPractical Celery
Practical Celery
 
Intro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJSIntro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJS
 
Javascript Testing with Jasmine 101
Javascript Testing with Jasmine 101Javascript Testing with Jasmine 101
Javascript Testing with Jasmine 101
 
AngularJS Unit Test
AngularJS Unit TestAngularJS Unit Test
AngularJS Unit Test
 
Good karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with KarmaGood karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with Karma
 
Painless JavaScript Testing with Jest
Painless JavaScript Testing with JestPainless JavaScript Testing with Jest
Painless JavaScript Testing with Jest
 
Angularjs - Unit testing introduction
Angularjs - Unit testing introductionAngularjs - Unit testing introduction
Angularjs - Unit testing introduction
 
Angular testing
Angular testingAngular testing
Angular testing
 
We Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentWe Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End Development
 
Celery: The Distributed Task Queue
Celery: The Distributed Task QueueCelery: The Distributed Task Queue
Celery: The Distributed Task Queue
 

Viewers also liked

Combustion & Flue Gas Analysis
Combustion & Flue Gas AnalysisCombustion & Flue Gas Analysis
Combustion & Flue Gas Analysis
Amit Makwana
 
Measurement of ambient air pollutants, sampling and analysis
Measurement of ambient air pollutants, sampling and analysisMeasurement of ambient air pollutants, sampling and analysis
Measurement of ambient air pollutants, sampling and analysis
Abhishek Tiwari
 

Viewers also liked (10)

Dependency Inversion in large-scale TypeScript applications with InversifyJS
Dependency Inversion in large-scale TypeScript applications with InversifyJSDependency Inversion in large-scale TypeScript applications with InversifyJS
Dependency Inversion in large-scale TypeScript applications with InversifyJS
 
FTIR For Stack and CEM
FTIR For Stack and CEMFTIR For Stack and CEM
FTIR For Stack and CEM
 
Dr bhargava
Dr bhargavaDr bhargava
Dr bhargava
 
L 37 final
L 37 finalL 37 final
L 37 final
 
Combustion & Flue Gas Analysis
Combustion & Flue Gas AnalysisCombustion & Flue Gas Analysis
Combustion & Flue Gas Analysis
 
Air quality montoring system
Air quality montoring systemAir quality montoring system
Air quality montoring system
 
Flue gas analisys in industry-Practical guide for Emission and Process Measur...
Flue gas analisys in industry-Practical guide for Emission and Process Measur...Flue gas analisys in industry-Practical guide for Emission and Process Measur...
Flue gas analisys in industry-Practical guide for Emission and Process Measur...
 
Measurement of ambient air pollutants, sampling and analysis
Measurement of ambient air pollutants, sampling and analysisMeasurement of ambient air pollutants, sampling and analysis
Measurement of ambient air pollutants, sampling and analysis
 
Air quality sampling and monitoring m5
Air quality sampling and monitoring m5Air quality sampling and monitoring m5
Air quality sampling and monitoring m5
 
Flue gas analysis
Flue gas analysisFlue gas analysis
Flue gas analysis
 

Similar to Full Stack Unit Testing

Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
Ran Mizrahi
 
Test strategy for web development
Test strategy for web developmentTest strategy for web development
Test strategy for web development
alice yang
 
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockUnit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Robot Media
 

Similar to Full Stack Unit Testing (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
 
Unit Testing from Setup to Deployment
Unit Testing from Setup to DeploymentUnit Testing from Setup to Deployment
Unit Testing from Setup to Deployment
 
Testing in JavaScript
Testing in JavaScriptTesting in JavaScript
Testing in JavaScript
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
 
Test strategy for web development
Test strategy for web developmentTest strategy for web development
Test strategy for web development
 
Javascript tdd byandreapaciolla
Javascript tdd byandreapaciollaJavascript tdd byandreapaciolla
Javascript tdd byandreapaciolla
 
Unit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and HowsUnit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and Hows
 
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
 
Browser testing with nightwatch.js - Drupal Europe
Browser testing with nightwatch.js - Drupal EuropeBrowser testing with nightwatch.js - Drupal Europe
Browser testing with nightwatch.js - Drupal Europe
 
Rapid prototyping and easy testing with ember cli mirage
Rapid prototyping and easy testing with ember cli mirageRapid prototyping and easy testing with ember cli mirage
Rapid prototyping and easy testing with ember cli mirage
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testing
 
Unit testing with Spock Framework
Unit testing with Spock FrameworkUnit testing with Spock Framework
Unit testing with Spock Framework
 
Performance and Scalability Testing with Python and Multi-Mechanize
Performance and Scalability Testing with Python and Multi-MechanizePerformance and Scalability Testing with Python and Multi-Mechanize
Performance and Scalability Testing with Python and Multi-Mechanize
 
Protractor framework architecture with example
Protractor framework architecture with exampleProtractor framework architecture with example
Protractor framework architecture with example
 
MT_01_unittest_python.pdf
MT_01_unittest_python.pdfMT_01_unittest_python.pdf
MT_01_unittest_python.pdf
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testing
 
Leveling Up With Unit Testing - php[tek] 2023
Leveling Up With Unit Testing - php[tek] 2023Leveling Up With Unit Testing - php[tek] 2023
Leveling Up With Unit Testing - php[tek] 2023
 
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockUnit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
 
UI Testing Best Practices - An Expected Journey
UI Testing Best Practices - An Expected JourneyUI Testing Best Practices - An Expected Journey
UI Testing Best Practices - An Expected Journey
 
Angularjs Test Driven Development (TDD)
Angularjs Test Driven Development (TDD)Angularjs Test Driven Development (TDD)
Angularjs Test Driven Development (TDD)
 

More from GlobalLogic Ukraine

GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
GlobalLogic Ukraine
 

More from GlobalLogic Ukraine (20)

GlobalLogic Embedded Community x ROS Ukraine Webinar "Surgical Robots"
GlobalLogic Embedded Community x ROS Ukraine Webinar "Surgical Robots"GlobalLogic Embedded Community x ROS Ukraine Webinar "Surgical Robots"
GlobalLogic Embedded Community x ROS Ukraine Webinar "Surgical Robots"
 
GlobalLogic Java Community Webinar #17 “SpringJDBC vs JDBC. Is Spring a Hero?”
GlobalLogic Java Community Webinar #17 “SpringJDBC vs JDBC. Is Spring a Hero?”GlobalLogic Java Community Webinar #17 “SpringJDBC vs JDBC. Is Spring a Hero?”
GlobalLogic Java Community Webinar #17 “SpringJDBC vs JDBC. Is Spring a Hero?”
 
GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”
GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”
GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”
 
Штучний інтелект як допомога в навчанні, а не замінник.pptx
Штучний інтелект як допомога в навчанні, а не замінник.pptxШтучний інтелект як допомога в навчанні, а не замінник.pptx
Штучний інтелект як допомога в навчанні, а не замінник.pptx
 
Задачі AI-розробника як застосовується штучний інтелект.pptx
Задачі AI-розробника як застосовується штучний інтелект.pptxЗадачі AI-розробника як застосовується штучний інтелект.pptx
Задачі AI-розробника як застосовується штучний інтелект.pptx
 
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptxЩо треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
 
GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...
GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...
GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...
 
JavaScript Community Webinar #14 "Why Is Git Rebase?"
JavaScript Community Webinar #14 "Why Is Git Rebase?"JavaScript Community Webinar #14 "Why Is Git Rebase?"
JavaScript Community Webinar #14 "Why Is Git Rebase?"
 
GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...
GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...
GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...
 
Страх і сила помилок - IT Inside від GlobalLogic Education
Страх і сила помилок - IT Inside від GlobalLogic EducationСтрах і сила помилок - IT Inside від GlobalLogic Education
Страх і сила помилок - IT Inside від GlobalLogic Education
 
GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”
GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”
GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”
 
GlobalLogic QA Webinar “What does it take to become a Test Engineer”
GlobalLogic QA Webinar “What does it take to become a Test Engineer”GlobalLogic QA Webinar “What does it take to become a Test Engineer”
GlobalLogic QA Webinar “What does it take to become a Test Engineer”
 
“How to Secure Your Applications With a Keycloak?
“How to Secure Your Applications With a Keycloak?“How to Secure Your Applications With a Keycloak?
“How to Secure Your Applications With a Keycloak?
 
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
 
GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...
GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...
GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...
 
GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”
GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”
GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”
 
Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"
Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"
Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"
 
GlobalLogic Webinar "Introduction to Embedded QA"
GlobalLogic Webinar "Introduction to Embedded QA"GlobalLogic Webinar "Introduction to Embedded QA"
GlobalLogic Webinar "Introduction to Embedded QA"
 
C++ Webinar "Why Should You Learn C++ in 2021-22?"
C++ Webinar "Why Should You Learn C++ in 2021-22?"C++ Webinar "Why Should You Learn C++ in 2021-22?"
C++ Webinar "Why Should You Learn C++ in 2021-22?"
 
GlobalLogic Test Automation Live Testing Session “Android Behind UI — Testing...
GlobalLogic Test Automation Live Testing Session “Android Behind UI — Testing...GlobalLogic Test Automation Live Testing Session “Android Behind UI — Testing...
GlobalLogic Test Automation Live Testing Session “Android Behind UI — Testing...
 

Recently uploaded

Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Kandungan 087776558899
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
Neometrix_Engineering_Pvt_Ltd
 
Hospital management system project report.pdf
Hospital management system project report.pdfHospital management system project report.pdf
Hospital management system project report.pdf
Kamal Acharya
 

Recently uploaded (20)

Online electricity billing project report..pdf
Online electricity billing project report..pdfOnline electricity billing project report..pdf
Online electricity billing project report..pdf
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equation
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdf
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the start
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS Lambda
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
 
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptxHOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
 
PE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and propertiesPE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and properties
 
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
AIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsAIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech students
 
Engineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planesEngineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planes
 
Hospital management system project report.pdf
Hospital management system project report.pdfHospital management system project report.pdf
Hospital management system project report.pdf
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna Municipality
 
Online food ordering system project report.pdf
Online food ordering system project report.pdfOnline food ordering system project report.pdf
Online food ordering system project report.pdf
 
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
 

Full Stack Unit Testing

  • 2. Plan 1. Overview of frameworks and libraries for testing 2. Testing of client side web application a. Test runner b. Unit testing stack c. End-2-end testing d. Reporting e. Sample: angular application testing 3. Testing of server side a. Mocking of data providers b. Fixtures c. Essentials of tests 4. Pitfalls of unit testing
  • 4. Testing of client-side 1. Test runner - runs unit tests suite in various browsers and write reports using different formats 2. Frameworks - skeleton for unit tests suites 3. Utils libraries - allow to write tests in more expressive
  • 5. Test runner 1. Dynamically generate index file using required libs, sources and tests 2. Execute web server on background 3. Run tests in different browsers 4. Collect test results from expectations and asserts 5. Format them into report
  • 6. Test runner Test’em - simple test runner 1. Framework config: Mocha, Jasmine 2. Test files 3. Serve files 4. Browser stack config
  • 7. Test runner Karma - advanced test runner 1. Plugins 2. Multiple report formats supported 3. Various browsers 4. Dynamic index.html generation
  • 8. Test runner Essentials 1. Synchronization between source files 2. Integration of frameworks 3. Debugging
  • 9. Unit testing stack Testing framework API ● TDD ● BDD Main frameworks ● Mocha ● Jasmine ● describe o skip o only ● it ● before(done) ● after(done) ● beforeEach ● afterEach
  • 10. Unit testing stack Assertion libraries Chai ● Plugins ● Supports should and expect style Should ● expect(foo).to.deep. equal(someNested Array) ● should.exist(foo) ● foo.bar.should.have .property(‘bar’)
  • 11. Unit testing stack Plugins for chai ● Allows you to write tests in terms of libraries you are using ● Syntactic sugar ● Sinon.js ● jQuery ● Backbone ● Q
  • 13. End-2-end testing Protractor (previously angular-scenario): ● Access to angular scope from view ● Selectors for directives ● Uses selenium ● by. o id o css o model o binding ● element o sendKeys o setPosition o setSize
  • 15. Reporting ● jUnit XML - Jenkins love it ● Progress, Dots - for console lovers ● Coverage - objective metrics ● jUnit is has better support of Jasmine ● Coverage settings - include all sources not tests
  • 17.
  • 18. Sample angular app testing beforeEach(inject(function ($controller, $rootScope) { scope = $rootScope.$new(); GamesCtrl = $controller('HotelsCtrl', { $scope: scope, Hotels: factory }); })); it('should set default value for orderProp', function () { expect(scope.orderProp).toBe('title'); }); it('should have a List of Hotels', function () { expect(scope.games.length).toBe(2); expect(scope.games[0].title).toBe('Hilton'); expect(scope.games[1].freeRooms).toBe(10); });
  • 20. Mocking of data providers Faker.js ● id’s ● names, emails ● cities, locations ● messages, sentences, paragraphs Sinon.js ● Mocking API using sinon.mock(API)
  • 21. Sample code //Hotels data 'use strict'; var Faker = require('Faker'); function generateOne() { return { name: Faker.random.bk_noun(), address: Faker.Addresses.streetAddress(), capacity: { standard: Faker.helpers.randomNumber(100), economy: Faker.helpers.randomNumber(100), luxury: Faker.helpers.randomNumber(100) } }; } module.exports.generateOne = generateOne; module.exports.generateMany = function (count) { var result = []; for (var i = 0; i < count; i++) { result.push(generateOne()) } return result; }
  • 22. Database mapping testing 1. No need to test mongoose API 2. Create stub data using Faker API and predefined JSON 3. Insert it into DB inside before callback 4. Run unit test suites on test data 5. Remove data from DB inside after callback
  • 23. Sample code var fixtures = require('fixtures.js'); var api = require('api/'); var expect = require('chai').expect; var COUNT = 100; describe('Booking API', function () { describe('#search', function () { before(function (done) { fixtures.prepareData('hotels', COUNT, done); }); it('should return all hotes if no query params provided', function (done) {api.search('hotels', function (err, data) { expect(err).to.be.null; expect(data).to.be.an('object'); expect(data.length).to.be.eql(COUNT); done(); …. after(function (done) { fixtures.destroyData('hotels');
  • 24. Alternatives ● https://github.com/petejkim/factory-lady ● http://chaijs.com/plugins/chai-factories ● https://www.npmjs.com/package/rosie
  • 25. Fixtures Rules 1. Do not hardcode the id’s and data that is generated by database 2. Put all domain specific data into fixtures, group them by collections 3. Do not put null to client API object. Use dummy object instead.
  • 26. Sample code // Fixtures var async = require('async'); var hotelsData = require('./hotelsData'); var Hotel = require('./hotelModel'); module.exports.prepareData = function (name, count, cb) { if (name !== 'hotels') { cb(new Error('Invalid data type')); return; } async.forEach(hotelsData.generateMany(count), function (item, callback) { var hotel = Hotel.createNew(item); hotel.save(callback); }, cb) }
  • 27. Sample code var client = null; function notInitializedThrow () {throw new Error ('Client not initialized')}; module.exports.init = function (config, cb) { if (client === null) { client = API.createClient(config); // doing some initializations tuff client.on('error', cb); client.on('connected', cb.bind(this, null)); } } module.exports.getClient = function () { if (client === null) { return { method1: notInitializedThrow, method2: notInitializedThrow } } else { return client; } }
  • 28. Essentials 1. Test should not depend on each others results 2. They should not use shared data (only in read only mode) 3. Do not allow skipped tests in releases 4. Tests are not just for make it green
  • 29. Integration tests 1. They are checking of how modules are working together 2. Ideal for checking of entity lifecycle - creation, linking to others, api calls, querying, destroying 3. Execution environment should be configurable
  • 30.
  • 31.
  • 32. References Tools: ● WS: o WebSocket API client ● HTTP: o Nock Article: ● https://davidbeath.com/posts/testing-http-responses-in-nodejs. html
  • 33. Stack 1. Mocha as core framework 2. Chai / Expect as assertions 3. Request.js for HTTP requests 4. node-websocket as ws client 5. Faker or factory-lady for generation of test data
  • 34. Best 1. To put grunt test or test command as git merge to master hook 2. To put shortcut for testing into npm test assuming that grunt is not globally installed 3. JSHint/JSLint as pre commit hook
  • 35. Worst 1. To mix TDD and BDD a. TDD: Suite, test, step, setup, done b. BDD: Expectations, asserts 2. To spaghetti the dependencies inside test code
  • 36. Sample code describe('API method', function () { var temporaryData = null; it('should do one thing', function (done) { var result = API.call('somemethod'); temporaryData = API.call('anotherMethod'); expect(result).to.have.keys(['code', 'details', 'message']); }); it('should do another thing', function (done) { API.call('setup', temporaryData); var result = API.call('anotherMethod'); expect(result).to.be.null;
  • 37. Pitfalls 1. Separated environment for integration testing, unit testing development and production 2. Do not rely on synchronous operations especially when they are not (callbacks, initialization process) 3. Extra console.log’s are breaking unit test reportings
  • 38. Sample code describe('Service API', function () { before(function (done) { thirdparty1.init(/*callback?*/); thirdparty2.init(/*callback?*/); thirdparty3.init(/*callback?*/); done(); }); before(function (done) { thirdparty1.done(/*callback?*/); thirdparty2.done(/*callback?*/); thirdparty3.done(/*callback?*/); done(); }); }); describe('Service API', function () { before(function (done) { async.waterfall([ thirdparty1.init, thirdparty2.init, thirdparty3.init ], done); }); before(function (done) { async.waterfall([ thirdparty1.done, thirdparty2.done, thirdparty3.done ], done); }); });
  • 39. References Books 1. Testable Javascript book 2. JavaScript Allongé 3. Testing with CoffeeScript Articles/Blogs: 1. Full spectrum testing with angular.js and Karma 2. Cross-browser testing on multiple devices 3. Mocha + CoffeeScript tutorial 4. http://code.tutsplus.com/tutorials/testing-in-nodejs--net-35018
  • 40. Tools 1. Node version manager 2. Mocha 3. Jasmine 4. Karma 5. Istanbul 6. Protractor 7. Selenium
  • 41. QA