SlideShare a Scribd company logo
Testing most things
in JavaScript
Leeds JS
Colin Oakley
@htmlandbacon
HELLO
why do we test ?
reassurance
quality
automation
side effects
types of testing
unit
intergration
acceptance
unit testing in
javascript
testing frameworks
• mocha
• jasmine
• jest
• ava
• TAP
example code
module.exports = {
format(firstName = '', lastName = '') {
let string = '';
if(firstName != '') {
string = firstName;
}
if(lastName != '') {
if(string.length === 0) {
string = lastName;
} else {
string = string + ' ' + lastName;
}
}
return string.toUpperCase();
}
};
example unit tests
const mocha = require('mocha');
const assert = require('chai').assert;
const name = require('../examples/nameFormatter');
const firstName = 'Kevin';
const lastName = 'Flynn';
describe('calling name.format(firstName, lastName)', function() {
it('should return empty string when nothing is supplied', function() {
const returendName = name.format();
assert.equal(returendName, '');
});
it('should return uppercase first name when firstName is provided', function() {
const returendName = name.format(firstName);
assert.equal(returendName, 'KEVIN');
});
it('should return uppercase firstName and lastName when both are provided', function() {
const returendName = name.format(firstName, lastName);
assert.equal(returendName, 'KEVIN FLYNN');
});
});
example output
calling name.format(firstName, lastName)
✓ should return empty string when nothing is supplied
✓ should return uppercase first name when firstName is provided
✓ should return uppercase firstName and lastName when both are provided
hinting for failure
it('should return uppercase first name when firstName is provided', function() {
const returendName = name.format(firstName);
assert.equal(returendName, 'KEVIN', 'uppercase first name not found');
});
failed output
calling name.format(firstName, lastName)
✓ should return empty string when nothing is supplied
1) should return uppercase first name when firstName is provided
2) should return uppercase firstName and lastName when both are provided
1 passing (12ms)
2 failing
1) calling name.format(firstName, lastName) should return uppercase first name when firstName is provided:
AssertionError: uppercase first name not found: expected 'Kevin' to equal 'KEVIN'
at Context.<anonymous> (test/index.js:16:12)
2) calling name.format(firstName, lastName) should return uppercase firstName and lastName when both are provided:
AssertionError: uppercase whole name not found: expected 'Kevin Flynn' to equal 'KEVIN FLYNN'
at Context.<anonymous> (test/index.js:20:12)
mocha hooks
• before()
• after()
• beforeEach()
• afterEach()
assertions styles chai - BDD
• expect(foo).to.be.undefined;
• expect(everything).to.be.ok;
• expect(thing).to.include.members([3, 2]);
• expect(foo).to.be.above(5);
assertions styles chai - TDD
• assert.isUndefined(food)
• assert.isOkay(everything)
• assert.include(thing, [3, 2])
• assert.isAbove(5)
Jest
Jest - assertions
• expect(foo).toBeUndefined()
• expect(inputs).toBeTruthy()
• expect(foo).toBeDefined()
Jest - Snapshots
DOM
TDD
ci build
example ci build
1. code style check
2. run tests
3. coverage
4. deploy
5. start intergration tests
6. start accetance tests
code style
code style js
• Spacing (2 spaces, tabs, moons, whatever!)
• Single quotes for strings
• No unused variables
• No semicolons
• Space after keywords
• Space after function name
https://github.com/airbnb/javascript
code coverage
• istanbul
• sonar cube
• Blanket
• JScoverage
code coverage example
-------------------|----------|----------|----------|----------|----------------|
File | % Stmts | % Branch | % Funcs | % Lines |Uncovered Lines |
-------------------|----------|----------|----------|----------|----------------|
examples/ | 88.89 | 83.33 | 100 | 88.89 | |
nameFormatter.js | 88.89 | 83.33 | 100 | 88.89 | 12 |
-------------------|----------|----------|----------|----------|----------------|
All files | 88.89 | 83.33 | 100 | 88.89 | |
-------------------|----------|----------|----------|----------|----------------|
=============================== Coverage summary ===============================
Statements : 88.89% ( 8/9 )
Branches : 83.33% ( 5/6 )
Functions : 100% ( 1/1 )
Lines : 88.89% ( 8/9 )
================================================================================
mocks
spies
stubs
and pain
intergration
example intergration tests
const validUserID = 'A0001';
const invalidUserID = 'B0001';
describe('/api/users', function() {
describe('/:id', function() {
it('returns user when valid user id is given', function(done) {
superagent
.get(`http://localhost:${port}/api/users/${validUserID}`)
.end(function(err, res) {
assert.equal(res.status, status.OK);
const result = JSON.parse(res.text);
assert.equal(result.id, validUserID);
done();
});
});
it('returns 404 error with message when user does not exist', function(done) {
superagent
.get(`http://localhost:${port}/api/users/${invalidUserID}`)
.end(function(err, res) {
assert.equal(res.status, status.NOT_FOUND);
const result = JSON.parse(res.text);
assert.equal(result.message, `User ${invalidUserID} was not found.`);
done();
});
});
});
});
acceptance
acceptance testing frameworks
• NightwatchJS
• Intern
• WebDriverIO
example NightwatchJS
const base = (process.env.SITE || 'http://localhost:3000');
describe('Demo', function () {
describe('with Nightwatch', function () {
after(function (client, done) {
client.end(function () {
done();
});
});
afterEach(function (client, done) {
if (client.options.screenshots) {
client.saveScreenshot(client.currentTest.name + '.png');
}
done();
});
it('should access a page and assert a valid title', function (client) {
client
.url(base + '/docs/examples/elements/forms')
.expect.element('body').to.be.present.before(100);
client.assert.containsText('h1', 'Your details');
});
});
});
example cuecumber
NightwatchJS
# features/checkpage.feature
Feature: Check page title
Scenario: Acccessing page
Given I open the form elements page
Then the title is "Your detail"
And I don't even know
MORE TESTING
a11y
automated tools
• aXe
• pa11y
• tenon
• HTML Codesniffer
pally example
pa11y words.htmlandbacon.com
Welcome to Pa11y
> PhantomJS browser created
> Testing the page "http://words.htmlandbacon.com"
Results for words.htmlandbacon.com:
• Notice: Check that the title element describes the document.
├── WCAG2AA.Principle2.Guideline2_4.2_4_2.H25.2
├── html > head > title
└── <title>html &amp; bacon - The rambling...</title>
0 Errors
0 Warnings
24 Notices
visual regression
getting started
1. npm install -g backstopjs
2. backstop genConfig
3. Tweak url / css selectors in json
4. backstop reference
5. backstop test
backstop.js - example
in summary
KTHXBYE

More Related Content

What's hot

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
 
How To Test Everything
How To Test EverythingHow To Test Everything
How To Test Everything
noelrap
 
Painless JavaScript Testing with Jest
Painless JavaScript Testing with JestPainless JavaScript Testing with Jest
Painless JavaScript Testing with Jest
Michał Pierzchała
 
JavaScript TDD with Jasmine and Karma
JavaScript TDD with Jasmine and KarmaJavaScript TDD with Jasmine and Karma
JavaScript TDD with Jasmine and Karma
Christopher Bartling
 
Testing Java Code Effectively - BaselOne17
Testing Java Code Effectively - BaselOne17Testing Java Code Effectively - BaselOne17
Testing Java Code Effectively - BaselOne17
Andres Almiray
 
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
Andrey Kolodnitsky
 
Testing javascript in the frontend
Testing javascript in the frontendTesting javascript in the frontend
Testing javascript in the frontend
Frederic CABASSUT
 
JavaScript Unit Testing with Jasmine
JavaScript Unit Testing with JasmineJavaScript Unit Testing with Jasmine
JavaScript Unit Testing with Jasmine
Raimonds Simanovskis
 
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
Gil Fink
 
Testing your javascript code with jasmine
Testing your javascript code with jasmineTesting your javascript code with jasmine
Testing your javascript code with jasmineRubyc Slides
 
Introduction to Protractor
Introduction to ProtractorIntroduction to Protractor
Introduction to Protractor
Jie-Wei Wu
 
TDAD
TDADTDAD
Unit testing of java script and angularjs application using Karma Jasmine Fra...
Unit testing of java script and angularjs application using Karma Jasmine Fra...Unit testing of java script and angularjs application using Karma Jasmine Fra...
Unit testing of java script and angularjs application using Karma Jasmine Fra...
Samyak Bhalerao
 
Code generation for alternative languages
Code generation for alternative languagesCode generation for alternative languages
Code generation for alternative languages
Rafael Winterhalter
 
Unit Testing with Jest
Unit Testing with JestUnit Testing with Jest
Unit Testing with Jest
Maayan Glikser
 
Migrating to JUnit 5
Migrating to JUnit 5Migrating to JUnit 5
Migrating to JUnit 5
Rafael Winterhalter
 
Getting Testy With Perl6
Getting Testy With Perl6Getting Testy With Perl6
Getting Testy With Perl6
Workhorse Computing
 
Test driven node.js
Test driven node.jsTest driven node.js
Test driven node.js
Jay Harris
 
Unit testing concurrent code
Unit testing concurrent codeUnit testing concurrent code
Unit testing concurrent code
Rafael Winterhalter
 

What's hot (20)

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
 
How To Test Everything
How To Test EverythingHow To Test Everything
How To Test Everything
 
Painless JavaScript Testing with Jest
Painless JavaScript Testing with JestPainless JavaScript Testing with Jest
Painless JavaScript Testing with Jest
 
JavaScript TDD with Jasmine and Karma
JavaScript TDD with Jasmine and KarmaJavaScript TDD with Jasmine and Karma
JavaScript TDD with Jasmine and Karma
 
Testing Java Code Effectively - BaselOne17
Testing Java Code Effectively - BaselOne17Testing Java Code Effectively - BaselOne17
Testing Java Code Effectively - BaselOne17
 
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
 
Testing javascript in the frontend
Testing javascript in the frontendTesting javascript in the frontend
Testing javascript in the frontend
 
JavaScript Unit Testing with Jasmine
JavaScript Unit Testing with JasmineJavaScript Unit Testing with Jasmine
JavaScript Unit Testing with Jasmine
 
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
 
Testing your javascript code with jasmine
Testing your javascript code with jasmineTesting your javascript code with jasmine
Testing your javascript code with jasmine
 
Introduction to Protractor
Introduction to ProtractorIntroduction to Protractor
Introduction to Protractor
 
jasmine
jasminejasmine
jasmine
 
TDAD
TDADTDAD
TDAD
 
Unit testing of java script and angularjs application using Karma Jasmine Fra...
Unit testing of java script and angularjs application using Karma Jasmine Fra...Unit testing of java script and angularjs application using Karma Jasmine Fra...
Unit testing of java script and angularjs application using Karma Jasmine Fra...
 
Code generation for alternative languages
Code generation for alternative languagesCode generation for alternative languages
Code generation for alternative languages
 
Unit Testing with Jest
Unit Testing with JestUnit Testing with Jest
Unit Testing with Jest
 
Migrating to JUnit 5
Migrating to JUnit 5Migrating to JUnit 5
Migrating to JUnit 5
 
Getting Testy With Perl6
Getting Testy With Perl6Getting Testy With Perl6
Getting Testy With Perl6
 
Test driven node.js
Test driven node.jsTest driven node.js
Test driven node.js
 
Unit testing concurrent code
Unit testing concurrent codeUnit testing concurrent code
Unit testing concurrent code
 

Similar to Testing most things in JavaScript - LeedsJS 31/05/2017

All you need to know about Callbacks, Promises, Generators
All you need to know about Callbacks, Promises, GeneratorsAll you need to know about Callbacks, Promises, Generators
All you need to know about Callbacks, Promises, Generators
Brainhub
 
A Lifecycle Of Code Under Test by Robert Fornal
A Lifecycle Of Code Under Test by Robert FornalA Lifecycle Of Code Under Test by Robert Fornal
A Lifecycle Of Code Under Test by Robert Fornal
QA or the Highway
 
Stop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScriptStop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScript
Ryan Anklam
 
The Future of JVM Languages
The Future of JVM Languages The Future of JVM Languages
The Future of JVM Languages
VictorSzoltysek
 
BDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
BDD - Behavior Driven Development Webapps mit Groovy Spock und GebBDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
BDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
Christian Baranowski
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bitsChris Saylor
 
Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1
Troy Miles
 
Concurrency on the JVM
Concurrency on the JVMConcurrency on the JVM
Concurrency on the JVMVaclav Pech
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11
Michelangelo van Dam
 
Google guava
Google guavaGoogle guava
Groovy Basics
Groovy BasicsGroovy Basics
Groovy Basics
Wes Williams
 
Automated javascript unit testing
Automated javascript unit testingAutomated javascript unit testing
Automated javascript unit testingryan_chambers
 
Typescript barcelona
Typescript barcelonaTypescript barcelona
Typescript barcelona
Christoffer Noring
 
Koajs as an alternative to Express - OdessaJs'16
Koajs as an alternative to Express - OdessaJs'16Koajs as an alternative to Express - OdessaJs'16
Koajs as an alternative to Express - OdessaJs'16
Nikolay Kozhukharenko
 
Cool JVM Tools to Help You Test
Cool JVM Tools to Help You TestCool JVM Tools to Help You Test
Cool JVM Tools to Help You Test
Schalk Cronjé
 
Spock
SpockSpock
Spock
nklmish
 
Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)
David Atchley
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
cacois
 
Unit Testing Front End JavaScript
Unit Testing Front End JavaScriptUnit Testing Front End JavaScript
Unit Testing Front End JavaScript
FITC
 

Similar to Testing most things in JavaScript - LeedsJS 31/05/2017 (20)

All you need to know about Callbacks, Promises, Generators
All you need to know about Callbacks, Promises, GeneratorsAll you need to know about Callbacks, Promises, Generators
All you need to know about Callbacks, Promises, Generators
 
A Lifecycle Of Code Under Test by Robert Fornal
A Lifecycle Of Code Under Test by Robert FornalA Lifecycle Of Code Under Test by Robert Fornal
A Lifecycle Of Code Under Test by Robert Fornal
 
Stop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScriptStop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScript
 
The Future of JVM Languages
The Future of JVM Languages The Future of JVM Languages
The Future of JVM Languages
 
BDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
BDD - Behavior Driven Development Webapps mit Groovy Spock und GebBDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
BDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bits
 
Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1
 
Concurrency on the JVM
Concurrency on the JVMConcurrency on the JVM
Concurrency on the JVM
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11
 
Google guava
Google guavaGoogle guava
Google guava
 
Groovy Basics
Groovy BasicsGroovy Basics
Groovy Basics
 
Automated javascript unit testing
Automated javascript unit testingAutomated javascript unit testing
Automated javascript unit testing
 
Typescript barcelona
Typescript barcelonaTypescript barcelona
Typescript barcelona
 
Koajs as an alternative to Express - OdessaJs'16
Koajs as an alternative to Express - OdessaJs'16Koajs as an alternative to Express - OdessaJs'16
Koajs as an alternative to Express - OdessaJs'16
 
Cool JVM Tools to Help You Test
Cool JVM Tools to Help You TestCool JVM Tools to Help You Test
Cool JVM Tools to Help You Test
 
Spock
SpockSpock
Spock
 
Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
 
Php & my sql
Php & my sqlPhp & my sql
Php & my sql
 
Unit Testing Front End JavaScript
Unit Testing Front End JavaScriptUnit Testing Front End JavaScript
Unit Testing Front End JavaScript
 

Recently uploaded

Vaccine management system project report documentation..pdf
Vaccine management system project report documentation..pdfVaccine management system project report documentation..pdf
Vaccine management system project report documentation..pdf
Kamal Acharya
 
TECHNICAL TRAINING MANUAL GENERAL FAMILIARIZATION COURSE
TECHNICAL TRAINING MANUAL   GENERAL FAMILIARIZATION COURSETECHNICAL TRAINING MANUAL   GENERAL FAMILIARIZATION COURSE
TECHNICAL TRAINING MANUAL GENERAL FAMILIARIZATION COURSE
DuvanRamosGarzon1
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
obonagu
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
SamSarthak3
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
Kamal Acharya
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
Jayaprasanna4
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
Amil Baba Dawood bangali
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
Kamal Acharya
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
MdTanvirMahtab2
 
Halogenation process of chemical process industries
Halogenation process of chemical process industriesHalogenation process of chemical process industries
Halogenation process of chemical process industries
MuhammadTufail242431
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
ankuprajapati0525
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
VENKATESHvenky89705
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
Intella Parts
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
AafreenAbuthahir2
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
JoytuBarua2
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation & Control
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
ViniHema
 
addressing modes in computer architecture
addressing modes  in computer architectureaddressing modes  in computer architecture
addressing modes in computer architecture
ShahidSultan24
 
Democratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek AryaDemocratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek Arya
abh.arya
 

Recently uploaded (20)

Vaccine management system project report documentation..pdf
Vaccine management system project report documentation..pdfVaccine management system project report documentation..pdf
Vaccine management system project report documentation..pdf
 
TECHNICAL TRAINING MANUAL GENERAL FAMILIARIZATION COURSE
TECHNICAL TRAINING MANUAL   GENERAL FAMILIARIZATION COURSETECHNICAL TRAINING MANUAL   GENERAL FAMILIARIZATION COURSE
TECHNICAL TRAINING MANUAL GENERAL FAMILIARIZATION COURSE
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
 
Halogenation process of chemical process industries
Halogenation process of chemical process industriesHalogenation process of chemical process industries
Halogenation process of chemical process industries
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
 
addressing modes in computer architecture
addressing modes  in computer architectureaddressing modes  in computer architecture
addressing modes in computer architecture
 
Democratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek AryaDemocratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek Arya
 

Testing most things in JavaScript - LeedsJS 31/05/2017

  • 1. Testing most things in JavaScript Leeds JS Colin Oakley @htmlandbacon
  • 3. why do we test ?
  • 10.
  • 12. testing frameworks • mocha • jasmine • jest • ava • TAP
  • 13. example code module.exports = { format(firstName = '', lastName = '') { let string = ''; if(firstName != '') { string = firstName; } if(lastName != '') { if(string.length === 0) { string = lastName; } else { string = string + ' ' + lastName; } } return string.toUpperCase(); } };
  • 14. example unit tests const mocha = require('mocha'); const assert = require('chai').assert; const name = require('../examples/nameFormatter'); const firstName = 'Kevin'; const lastName = 'Flynn'; describe('calling name.format(firstName, lastName)', function() { it('should return empty string when nothing is supplied', function() { const returendName = name.format(); assert.equal(returendName, ''); }); it('should return uppercase first name when firstName is provided', function() { const returendName = name.format(firstName); assert.equal(returendName, 'KEVIN'); }); it('should return uppercase firstName and lastName when both are provided', function() { const returendName = name.format(firstName, lastName); assert.equal(returendName, 'KEVIN FLYNN'); }); });
  • 15. example output calling name.format(firstName, lastName) ✓ should return empty string when nothing is supplied ✓ should return uppercase first name when firstName is provided ✓ should return uppercase firstName and lastName when both are provided
  • 16. hinting for failure it('should return uppercase first name when firstName is provided', function() { const returendName = name.format(firstName); assert.equal(returendName, 'KEVIN', 'uppercase first name not found'); });
  • 17. failed output calling name.format(firstName, lastName) ✓ should return empty string when nothing is supplied 1) should return uppercase first name when firstName is provided 2) should return uppercase firstName and lastName when both are provided 1 passing (12ms) 2 failing 1) calling name.format(firstName, lastName) should return uppercase first name when firstName is provided: AssertionError: uppercase first name not found: expected 'Kevin' to equal 'KEVIN' at Context.<anonymous> (test/index.js:16:12) 2) calling name.format(firstName, lastName) should return uppercase firstName and lastName when both are provided: AssertionError: uppercase whole name not found: expected 'Kevin Flynn' to equal 'KEVIN FLYNN' at Context.<anonymous> (test/index.js:20:12)
  • 18. mocha hooks • before() • after() • beforeEach() • afterEach()
  • 19. assertions styles chai - BDD • expect(foo).to.be.undefined; • expect(everything).to.be.ok; • expect(thing).to.include.members([3, 2]); • expect(foo).to.be.above(5);
  • 20. assertions styles chai - TDD • assert.isUndefined(food) • assert.isOkay(everything) • assert.include(thing, [3, 2]) • assert.isAbove(5)
  • 21. Jest
  • 22. Jest - assertions • expect(foo).toBeUndefined() • expect(inputs).toBeTruthy() • expect(foo).toBeDefined()
  • 24. DOM
  • 25. TDD
  • 27. example ci build 1. code style check 2. run tests 3. coverage 4. deploy 5. start intergration tests 6. start accetance tests
  • 29. code style js • Spacing (2 spaces, tabs, moons, whatever!) • Single quotes for strings • No unused variables • No semicolons • Space after keywords • Space after function name https://github.com/airbnb/javascript
  • 30. code coverage • istanbul • sonar cube • Blanket • JScoverage
  • 31. code coverage example -------------------|----------|----------|----------|----------|----------------| File | % Stmts | % Branch | % Funcs | % Lines |Uncovered Lines | -------------------|----------|----------|----------|----------|----------------| examples/ | 88.89 | 83.33 | 100 | 88.89 | | nameFormatter.js | 88.89 | 83.33 | 100 | 88.89 | 12 | -------------------|----------|----------|----------|----------|----------------| All files | 88.89 | 83.33 | 100 | 88.89 | | -------------------|----------|----------|----------|----------|----------------| =============================== Coverage summary =============================== Statements : 88.89% ( 8/9 ) Branches : 83.33% ( 5/6 ) Functions : 100% ( 1/1 ) Lines : 88.89% ( 8/9 ) ================================================================================
  • 34. example intergration tests const validUserID = 'A0001'; const invalidUserID = 'B0001'; describe('/api/users', function() { describe('/:id', function() { it('returns user when valid user id is given', function(done) { superagent .get(`http://localhost:${port}/api/users/${validUserID}`) .end(function(err, res) { assert.equal(res.status, status.OK); const result = JSON.parse(res.text); assert.equal(result.id, validUserID); done(); }); }); it('returns 404 error with message when user does not exist', function(done) { superagent .get(`http://localhost:${port}/api/users/${invalidUserID}`) .end(function(err, res) { assert.equal(res.status, status.NOT_FOUND); const result = JSON.parse(res.text); assert.equal(result.message, `User ${invalidUserID} was not found.`); done(); }); }); }); });
  • 36. acceptance testing frameworks • NightwatchJS • Intern • WebDriverIO
  • 37. example NightwatchJS const base = (process.env.SITE || 'http://localhost:3000'); describe('Demo', function () { describe('with Nightwatch', function () { after(function (client, done) { client.end(function () { done(); }); }); afterEach(function (client, done) { if (client.options.screenshots) { client.saveScreenshot(client.currentTest.name + '.png'); } done(); }); it('should access a page and assert a valid title', function (client) { client .url(base + '/docs/examples/elements/forms') .expect.element('body').to.be.present.before(100); client.assert.containsText('h1', 'Your details'); }); }); });
  • 38. example cuecumber NightwatchJS # features/checkpage.feature Feature: Check page title Scenario: Acccessing page Given I open the form elements page Then the title is "Your detail" And I don't even know
  • 40. a11y
  • 41. automated tools • aXe • pa11y • tenon • HTML Codesniffer
  • 42. pally example pa11y words.htmlandbacon.com Welcome to Pa11y > PhantomJS browser created > Testing the page "http://words.htmlandbacon.com" Results for words.htmlandbacon.com: • Notice: Check that the title element describes the document. ├── WCAG2AA.Principle2.Guideline2_4.2_4_2.H25.2 ├── html > head > title └── <title>html &amp; bacon - The rambling...</title> 0 Errors 0 Warnings 24 Notices
  • 44. getting started 1. npm install -g backstopjs 2. backstop genConfig 3. Tweak url / css selectors in json 4. backstop reference 5. backstop test