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
Testing most things in JavaScript - LeedsJS 31/05/2017
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 (20)

PDF
JavaScript Test-Driven Development with Jasmine 2.0 and Karma
Christopher Bartling
 
KEY
How To Test Everything
noelrap
 
PDF
Painless JavaScript Testing with Jest
Michał Pierzchała
 
PDF
JavaScript TDD with Jasmine and Karma
Christopher Bartling
 
PDF
Testing Java Code Effectively - BaselOne17
Andres Almiray
 
PPTX
Unit testing in JavaScript with Jasmine and Karma
Andrey Kolodnitsky
 
PDF
Testing javascript in the frontend
Frederic CABASSUT
 
PDF
JavaScript Unit Testing with Jasmine
Raimonds Simanovskis
 
PDF
Quick tour to front end unit testing using jasmine
Gil Fink
 
PDF
Testing your javascript code with jasmine
Rubyc Slides
 
PDF
Introduction to Protractor
Jie-Wei Wu
 
PPTX
jasmine
Asanka Indrajith
 
PPTX
Unit testing of java script and angularjs application using Karma Jasmine Fra...
Samyak Bhalerao
 
PPTX
Code generation for alternative languages
Rafael Winterhalter
 
PDF
Unit Testing with Jest
Maayan Glikser
 
PPTX
Migrating to JUnit 5
Rafael Winterhalter
 
PDF
Getting Testy With Perl6
Workhorse Computing
 
PDF
Test driven node.js
Jay Harris
 
PPTX
Unit testing concurrent code
Rafael Winterhalter
 
JavaScript Test-Driven Development with Jasmine 2.0 and Karma
Christopher Bartling
 
How To Test Everything
noelrap
 
Painless JavaScript Testing with Jest
Michał Pierzchała
 
JavaScript TDD with Jasmine and Karma
Christopher Bartling
 
Testing Java Code Effectively - BaselOne17
Andres Almiray
 
Unit testing in JavaScript with Jasmine and Karma
Andrey Kolodnitsky
 
Testing javascript in the frontend
Frederic CABASSUT
 
JavaScript Unit Testing with Jasmine
Raimonds Simanovskis
 
Quick tour to front end unit testing using jasmine
Gil Fink
 
Testing your javascript code with jasmine
Rubyc Slides
 
Introduction to Protractor
Jie-Wei Wu
 
Unit testing of java script and angularjs application using Karma Jasmine Fra...
Samyak Bhalerao
 
Code generation for alternative languages
Rafael Winterhalter
 
Unit Testing with Jest
Maayan Glikser
 
Migrating to JUnit 5
Rafael Winterhalter
 
Getting Testy With Perl6
Workhorse Computing
 
Test driven node.js
Jay Harris
 
Unit testing concurrent code
Rafael Winterhalter
 

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

PDF
All you need to know about Callbacks, Promises, Generators
Brainhub
 
PDF
A Lifecycle Of Code Under Test by Robert Fornal
QA or the Highway
 
PDF
Stop Making Excuses and Start Testing Your JavaScript
Ryan Anklam
 
PDF
The Future of JVM Languages
VictorSzoltysek
 
PDF
BDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
Christian Baranowski
 
PDF
Javascript: the important bits
Chris Saylor
 
PDF
Game Design and Development Workshop Day 1
Troy Miles
 
ODP
Concurrency on the JVM
Vaclav Pech
 
PDF
Unit testing with zend framework tek11
Michelangelo van Dam
 
PDF
Google guava
t fnico
 
PPT
Groovy Basics
Wes Williams
 
PPT
Automated javascript unit testing
ryan_chambers
 
PPTX
Typescript barcelona
Christoffer Noring
 
PPTX
Koajs as an alternative to Express - OdessaJs'16
Nikolay Kozhukharenko
 
PDF
Cool JVM Tools to Help You Test
Schalk Cronjé
 
PDF
Spock
nklmish
 
PDF
Idiomatic Javascript (ES5 to ES2015+)
David Atchley
 
PPTX
Avoiding Callback Hell with Async.js
cacois
 
PPTX
Php & my sql
Norhisyam Dasuki
 
PDF
Unit Testing Front End JavaScript
FITC
 
All you need to know about Callbacks, Promises, Generators
Brainhub
 
A Lifecycle Of Code Under Test by Robert Fornal
QA or the Highway
 
Stop Making Excuses and Start Testing Your JavaScript
Ryan Anklam
 
The Future of JVM Languages
VictorSzoltysek
 
BDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
Christian Baranowski
 
Javascript: the important bits
Chris Saylor
 
Game Design and Development Workshop Day 1
Troy Miles
 
Concurrency on the JVM
Vaclav Pech
 
Unit testing with zend framework tek11
Michelangelo van Dam
 
Google guava
t fnico
 
Groovy Basics
Wes Williams
 
Automated javascript unit testing
ryan_chambers
 
Typescript barcelona
Christoffer Noring
 
Koajs as an alternative to Express - OdessaJs'16
Nikolay Kozhukharenko
 
Cool JVM Tools to Help You Test
Schalk Cronjé
 
Spock
nklmish
 
Idiomatic Javascript (ES5 to ES2015+)
David Atchley
 
Avoiding Callback Hell with Async.js
cacois
 
Php & my sql
Norhisyam Dasuki
 
Unit Testing Front End JavaScript
FITC
 
Ad

Recently uploaded (20)

PPTX
Worm gear strength and wear calculation as per standard VB Bhandari Databook.
shahveer210504
 
PPTX
2025 CGI Congres - Surviving agile v05.pptx
Derk-Jan de Grood
 
PDF
Viol_Alessandro_Presentazione_prelaurea.pdf
dsecqyvhbowrzxshhf
 
PDF
PORTFOLIO Golam Kibria Khan — architect with a passion for thoughtful design...
MasumKhan59
 
PDF
Pressure Measurement training for engineers and Technicians
AIESOLUTIONS
 
PDF
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 
PPTX
VITEEE 2026 Exam Details , Important Dates
SonaliSingh127098
 
PDF
Water Industry Process Automation & Control Monthly July 2025
Water Industry Process Automation & Control
 
PDF
International Journal of Information Technology Convergence and services (IJI...
ijitcsjournal4
 
PDF
MAD Unit - 2 Activity and Fragment Management in Android (Diploma IT)
JappanMavani
 
PPTX
Evaluation and thermal analysis of shell and tube heat exchanger as per requi...
shahveer210504
 
PDF
AI TECHNIQUES FOR IDENTIFYING ALTERATIONS IN THE HUMAN GUT MICROBIOME IN MULT...
vidyalalltv1
 
PPTX
Element 11. ELECTRICITY safety and hazards
merrandomohandas
 
PPT
PPT2_Metal formingMECHANICALENGINEEIRNG .ppt
Praveen Kumar
 
PPTX
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
PPTX
Thermal runway and thermal stability.pptx
godow93766
 
PPTX
265587293-NFPA 101 Life safety code-PPT-1.pptx
chandermwason
 
PPTX
GitOps_Without_K8s_Training_detailed git repository
DanialHabibi2
 
PDF
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
PPTX
The Role of Information Technology in Environmental Protectio....pptx
nallamillisriram
 
Worm gear strength and wear calculation as per standard VB Bhandari Databook.
shahveer210504
 
2025 CGI Congres - Surviving agile v05.pptx
Derk-Jan de Grood
 
Viol_Alessandro_Presentazione_prelaurea.pdf
dsecqyvhbowrzxshhf
 
PORTFOLIO Golam Kibria Khan — architect with a passion for thoughtful design...
MasumKhan59
 
Pressure Measurement training for engineers and Technicians
AIESOLUTIONS
 
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 
VITEEE 2026 Exam Details , Important Dates
SonaliSingh127098
 
Water Industry Process Automation & Control Monthly July 2025
Water Industry Process Automation & Control
 
International Journal of Information Technology Convergence and services (IJI...
ijitcsjournal4
 
MAD Unit - 2 Activity and Fragment Management in Android (Diploma IT)
JappanMavani
 
Evaluation and thermal analysis of shell and tube heat exchanger as per requi...
shahveer210504
 
AI TECHNIQUES FOR IDENTIFYING ALTERATIONS IN THE HUMAN GUT MICROBIOME IN MULT...
vidyalalltv1
 
Element 11. ELECTRICITY safety and hazards
merrandomohandas
 
PPT2_Metal formingMECHANICALENGINEEIRNG .ppt
Praveen Kumar
 
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
Thermal runway and thermal stability.pptx
godow93766
 
265587293-NFPA 101 Life safety code-PPT-1.pptx
chandermwason
 
GitOps_Without_K8s_Training_detailed git repository
DanialHabibi2
 
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
The Role of Information Technology in Environmental Protectio....pptx
nallamillisriram
 
Ad

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