SlideShare a Scribd company logo
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End Developers
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End Developers
engineer at shopify.
haris —
instructor at
hackeryou.
haris —
tech apparel + pins
at repitsupply.com
haris —
FITC2017
@harismahmood89
@repitsupply
haris —
WORLD OF
TESTINGfo r F r o n t -E n d D e v e l o p e r s
A n I n t r o d u c t i o n t o t h e
a brief intro.
i didn’t know where to start.
testing seemed hard.
testing seemed confusing.
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End Developers
front-end has evolved incredibly.
ridiculous amount of libraries, tools,
frameworks to choose from.
explore various aspects of the testing
world to help you begin.
won’t explore every option.
the most commonly used.
why test?
faster than manual testing in
the long run.
verify previously tested code still
works as the app/product evolves.
tests act like self-updating
documentation.
test all edge/weird cases.
build rock-solid apps.
a couple stories.
nest - smart thermostat.
drained entire battery after
software update.
no heat during one of the
coldest times in 2016.
nissan airbag sensor software.
washington state’s prison
sentence reduction.
update released in 2002.
more then 3,000 prisoners
released early.
600 days.
people would potentially have
to go back to prison.
13 years.
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End Developers
cool, so what first?
linting — the first line of defence.
linting tools enforce defined
style rules.
ensures better readability.
highlights issues (particularly
syntax errors) before execution.
eslint.
companies share their eslint configs
that you can use as a starting point.
test tools + concepts.
tonnes of different types of
test tools.
various functionalities.
some tools provide more than
one functionality.
develop an ideal combination of tools as per
your preference / project requirement.
i. test frameworks.
provides the foundation to test your code.
ii. testing structure.
test code organization. usually organized in a
behaviour-driven-development (bdd) structure.
describe('calculator', function() {
		
		 // describes a module with nested "describe" functions
		 describe('add', function() {
		
		 // specify the expected behaviour
		 it('should add 2 numbers', function() {
		 // test assertions go here
		 })
		 })
		})
ii. assertions.
functions that ensure test results are
as expected.
// Jasmine
expect(houseName).toBeString()
expect(houseName).toEqual(‘Targaryen’)
// Chai
expect(houseName).to.be.a(‘string’)
expect(houseName).to.equal(‘Targaryen’)
iii. spies.
gather info about function calls. help
verify functions are called or not.
var user = {
		 ...
		 setName: function(name) {
		 this.name = name;
		 }
		}
		
		//Create spy
		var setNameSpy = sinon.spy(user, ‘setName');
		user.setName(‘Jon Snow’);
		
		console.log(setNameSpy.callCount); //output: 1
super helpful to test callbacks.
function myFunction(condition, callback) {
		 if(condition) {
		 callback();
		 }
		}
function myFunction(condition, callback) {
		 if(condition) {
		 callback();
		 }
		}
		
		describe('myFunction', function() {
		 it('should call the callback function', function() {
		 var callback = sinon.spy();
		
		 myFunction(true, callback);
		
		 assert(callback.calledOnce); // true
		 });
		});
iv. stubs.
allow you to replace functions with our
own to ensure a behaviour.
var account = {
...
isActive: function() { ... }
}
sinon.stub(account, ‘isActive').returns(true)
v. code coverage.
determines whether our test cases are
covering the entirety of an app’s codebase.
vi. generate + display tests.
display our tests and results.
test types.
unit tests.
unit tests.
test individual functions / classes. pass in
inputs and ensure expected output is returned.
integration tests.
integration tests.
test several functions/modules/components to
ensure they work together as expected.
functional tests.
functional tests.
test a scenario on the app/product.
snapshot tests.
snapshot tests.
compare resulting data to an expected one.
super useful for component structure testing.
tips + things to keep in mind.
start with unit tests. they are
quite often easier to write.
use a coverage tool to ensure
unit tests cover everything.
have unit, and integration
tests at least.
snapshot tests can be an alternative
to ui-based integration tests.
use the same tools for all
your tests if possible.
testing structure, syntax, assertion
functions, result reporting, etc.
choosing a framework.
the first thing you’ll want to do
is to pick a testing framework.
let’s examine some of the most
popular ones today.
jasmine.
provides everything you need out of box -
running environment, reporting, mocking tools,
assertion functions.
ready out of the box. you can still switch/add
features if needed.
jasmine.
extremely popular in the angular world.
jasmine.
relies on third party libraries and tools for
assertions, mocks, spies etc.
mocha.
a little harder to setup, but more flexible.
mocha.
built and recommended by facebook.
jest.
wraps jasmine, and adds features on top.
jest.
super impressive speeds and convenience.
jest.
mainly used for react apps, but can be used
elsewhere too.
jest.
other tools.
code coverage tool.
istanbul.
lets you run tests in browsers - real,
headless, and legacy.
karma.
the most popular assertion library.
chai.
testing utility for react apps built by
airbnb. allows for super easy asserts,
traversing the component outputs, etc.
enzyme.
provides spies, stubs and mocks.
sinon.
how should i start?
super quick to set up + get going, provides
tonnes of tooling built right in (due to
jasmine wrapping).
start with jest.
just write some tests.
you may end up changing to a
different framework + tools.
the basic concepts are the same
across them all.
quick example.
silly movie theatre app. let’s
check it out, setup jest and start
testing!
var list = [
		 {
		 name: 'Jurassic World 2',
		 showTime: '7:00pm',
		 ticketsRemaining: 47,
		 },
		 {
		 name: 'Star Wars: The Last Jedi',
		 showTime: '10:00pm',
		 ticketsRemaining: 22,
		 }
		]
app-folder
!"" app.js
!"" yarn.lock
#"" package.json
app-folder
!"" app.js
!"" yarn.lock
#"" package.json
function listMovies(list) {
		 return list.reduce((acc, item) => {
		 return `${acc} ${item.name} at ${item.showTime} has $
{item.ticketsRemaining} tickets left n`;
		 }, '');
		}
function listMovies(list) {
		 return list.reduce((acc, item) => {
		 return `${acc} ${item.name} at ${item.showTime} has $
{item.ticketsRemaining} tickets left n`;
		 }, '');
		}
Jurassic World 2 at 7:00pm has 47 tickets left
Star Wars: The Last Jedi at 10:00pm has 22 tickets left
function ticketsLeft(movie) {
		 return movie.ticketsRemaining > 0;
		}
function addMovieToList(list, name, showTime) {
		 let newList = list.slice();
		 newList.push({
		 name,
		 showTime,
		 ticketsRemaining: 100
		 });
		
		 return newList;
		}
function buyTickets(movie, quantity) {
		 const newRemaining = movie.ticketsRemaining - quantity;
		 if (newRemaining >= 0) {
		 return Object.assign(movie,
{ticketsRemaining: movie.ticketsRemaining - quantity});
		 } else {
		 return 'Error';
		 }
		}
module.exports = {
listMovies,
ticketsLeft,
buyTickets,
addMovieToList
}
let’s setup jest!
yarn add --dev jest
npm install --save-dev jest
update package.json
{
"name": "example-1",
"version": "1.0.0",
"main": "app.js",
"license": "MIT",
"devDependencies": {
"jest": "^21.1.0"
},
"scripts": {
"test": "jest"
}
}
npm test
and that is literally it.
let’s write some tests!
two main ways to have jest run your tests.
i. files with *.test.js
ii. files in a folder named __test__
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End Developers
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End Developers
function ticketsLeft(movie) {
		 return movie.ticketsRemaining > 0;
		}
const app = require('./app.js');
		
		describe('the movie app', () => {
		 describe('ticketsLeft', () => {
		 it('should return false when no tickets available', () => {
		
		 });
		 });
		});
const app = require('./app.js');
		
		describe('the movie app', () => {
		 describe('ticketsLeft', () => {
		 it('should return false when no tickets available', () => {
		
		 });
		 });
		});
it('should return false when no tickets available', () => {
		 const testMovie = {
		 ticketsRemaining: 0,
		 };
		});
it('should return false when no tickets available', () => {
		 const testMovie = {
		 ticketsRemaining: 0,
		 };
		 const result = app.ticketsLeft(testMovie);
		 const expected = false;		
		});
it('should return false when no tickets available', () => {
		 const testMovie = {
		 ticketsRemaining: 0,
		 };
		 const result = app.ticketsLeft(testMovie);
		 const expected = false;
		
		 expect(result).toEqual(expected);
		});
‘expect’ and ‘toBe’ are called matchers.
npm test
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End Developers
🎉
it('should return true when tickets are available', () => {
		 const testMovie = {
		 ticketsRemaining: 27,
		 };
		 const result = app.ticketsLeft(testMovie);
		 const expected = true;
		
		 expect(result).toEqual(expected);
		});
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End Developers
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End Developers
function listMovies(list) {
		 return list.reduce((acc, item) => {
		 return `${acc} ${item.name} at ${item.showTime} has $
{item.ticketsRemaining} tickets left n`;
		 }, '');
		}
describe('listMovies', () => {
		
		 it('should list movies, showtimes and tickets', () => {
		 var list = [
		 {
		 name: 'Jurassic World 2’, showTime: ‘7:00pm', ticketsRemaining: 47,
		 },
		 {
		 name: 'Star Wars: The Last Jedi’, showTime: ’10:00pm', ticketsRemaining: 22,
		 }
		 ];
		
		 const result = app.listMovies(list);
		 const expected = 'Jurassic World 2 at 7:00pm has 47 tickets left nStar Wars:
The Last Jedi at 10:00pm has 22 tickets left n';
		
		 expect(result).toEqual(expected);
		 });
		 });
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End Developers
Difference:
- Expected
+ Received
- Jurassic World 2 at 7:00pm has 47 tickets left
- Star Wars: The Last Jedi at 10:00pm has 22 tickets left
+ Jurassic World 2 at 7:00pm has 47 tickets left
+ Star Wars: The Last Jedi at 10:00pm has 22 tickets left
Difference:
- Expected
+ Received
- Jurassic World 2 at 7:00pm has 47 tickets left
- Star Wars: The Last Jedi at 10:00pm has 22 tickets left
+ Jurassic World 2 at 7:00pm has 47 tickets left
+ Star Wars: The Last Jedi at 10:00pm has 22 tickets left
function listMovies(list) {
		 return list.reduce((acc, item) => {
		 return `${acc} ${item.name} at ${item.showTime} has $
{item.ticketsRemaining} tickets left n`;
		 }, '');
		}
function listMovies(list) {
		 return list.reduce((acc, item) => {
		 return `${acc}${item.name} at ${item.showTime} has $
{item.ticketsRemaining} tickets left n`;
		 }, '');
		}
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End Developers
describe('addMovieToList', () => {
		 it('adds a movie to the movie list', () => {
		 const list = [
		 { name: 'Jurassic World 2’, showTime: ‘7:00pm', ticketsRemaining: 47 }
		 ];
		
		 const results = app.addMovieToList(list, 'Thor', '4:30pm');
		 const expected = [
		 { name: 'Jurassic World 2’, showTime: ‘7:00pm’, ticketsRemaining: 47 },
		 { name: ‘Thor', showTime: ‘4:30pm', ticketsRemaining: 100 }
		 ];
		
		 expect(results).toBe(expected);
		
		 });
		 });
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End Developers
Expected value to be (using ===):
Compared values have no visual difference. Looks like you
wanted to test for object/array equality with strict `toBe`
matcher. You probably need to use `toEqual` instead.
describe('addMovieToList', () => {
		 it('adds a movie to the movie list', () => {
		 const list = [
		 { name: 'Jurassic World 2’, showTime: ‘7:00pm', ticketsRemaining: 47 }
		 ];
		
		 const results = app.addMovieToList(list, 'Thor', '4:30pm');
		 const expected = [
		 { name: 'Jurassic World 2’, showTime: ‘7:00pm’, ticketsRemaining: 47 },
		 { name: ‘Thor', showTime: ‘4:30pm', ticketsRemaining: 100 }
		 ];
		 	 	 expect(results).toBe(expected);
		 expect(results).toEqual(expected);
		
		 });
		 });
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End Developers
other matchers.
toBeNull, toBeUndefined, toBeDefined, toBeTruthy,
toBeFalsy, toBeGreaterThan, toBeGreaterThanOrEqual,
toBeLessThan, toMatch, toContain ...
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End Developers
all done! i think?
let’s setup some code coverage!
update our test script.
"scripts": {
"test": "jest --coverage"
}
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End Developers
buyTickets()
add a watcher for continuous testing runs.
"scripts": {
"test": "jest --coverage --watch"
}
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End Developers
in conclusion.
the value of testing is immense.
the ecosystem is vast with tonnes
of options to choose from.
many options provide tooling for
specific requirements.
a few that are all-encompassing.
start simple.
customize + modify as you go.
most importantly —
most importantly — start.
thank-you!
thank-you! #beKind
thank-you! #beKind #repItSupply

More Related Content

PDF
Workshop 5: JavaScript testing
PDF
Google Guava - Core libraries for Java & Android
PDF
Google guava
KEY
Google Guava
KEY
Djangocon11: Monkeying around at New Relic
PDF
JavaScript and the AST
PPTX
The Groovy Puzzlers – The Complete 01 and 02 Seasons
PDF
Clean code with google guava jee conf
Workshop 5: JavaScript testing
Google Guava - Core libraries for Java & Android
Google guava
Google Guava
Djangocon11: Monkeying around at New Relic
JavaScript and the AST
The Groovy Puzzlers – The Complete 01 and 02 Seasons
Clean code with google guava jee conf

What's hot (20)

PPTX
Akka in-action
PDF
The core libraries you always wanted - Google Guava
PDF
PPTX
Java 8 Puzzlers [as presented at OSCON 2016]
PDF
Google Guava for cleaner code
PDF
Deep dive into Oracle ADF
PDF
ES2015 workflows
PPTX
Test-driven JavaScript Development - OPITZ CONSULTING - Tobias Bosch - Stefa...
PDF
Google Guava
PDF
Con5623 pdf 5623_001
PPT
Bsides
 
PPTX
AST - the only true tool for building JavaScript
PPT
Web Optimization Summit: Coding for Performance
PDF
Hidden rocks in Oracle ADF
PDF
Riga Dev Day 2016 - Having fun with Javassist
PDF
Google guava - almost everything you need to know
PDF
AST Rewriting Using recast and esprima
PDF
JavaOne 2015 - Having fun with Javassist
KEY
Unit testing en iOS @ MobileCon Galicia
PPTX
ES6 Overview
Akka in-action
The core libraries you always wanted - Google Guava
Java 8 Puzzlers [as presented at OSCON 2016]
Google Guava for cleaner code
Deep dive into Oracle ADF
ES2015 workflows
Test-driven JavaScript Development - OPITZ CONSULTING - Tobias Bosch - Stefa...
Google Guava
Con5623 pdf 5623_001
Bsides
 
AST - the only true tool for building JavaScript
Web Optimization Summit: Coding for Performance
Hidden rocks in Oracle ADF
Riga Dev Day 2016 - Having fun with Javassist
Google guava - almost everything you need to know
AST Rewriting Using recast and esprima
JavaOne 2015 - Having fun with Javassist
Unit testing en iOS @ MobileCon Galicia
ES6 Overview
Ad

Similar to FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End Developers (20)

PDF
33rd Degree 2013, Bad Tests, Good Tests
PPT
OO JS for AS3 Devs
PPT
2012 JDays Bad Tests Good Tests
PDF
2013 DevFest Vienna - Bad Tests, Good Tests
PDF
How to test complex SaaS applications - The family july 2014
PDF
WordPress Realtime - WordCamp São Paulo 2015
KEY
Object-Oriented JavaScript
KEY
Object-Oriented Javascript
PPTX
Workshop 1: Good practices in JavaScript
KEY
jQuery Anti-Patterns for Performance
KEY
jQuery Anti-Patterns for Performance & Compression
PPT
Test Infected Presentation
PDF
Jggug 2010 330 Grails 1.3 観察
PPT
JSConf: All You Can Leet
PDF
Ten useful JavaScript tips & best practices
PDF
Secrets of JavaScript Libraries
PDF
JAVA...With N.E.T_B.E.A.N.S___________________________________.pdf
PDF
Implement threads and a GUI interface using advanced Java Swing clas.pdf
PDF
Integration Project Inspection 3
KEY
Android workshop
33rd Degree 2013, Bad Tests, Good Tests
OO JS for AS3 Devs
2012 JDays Bad Tests Good Tests
2013 DevFest Vienna - Bad Tests, Good Tests
How to test complex SaaS applications - The family july 2014
WordPress Realtime - WordCamp São Paulo 2015
Object-Oriented JavaScript
Object-Oriented Javascript
Workshop 1: Good practices in JavaScript
jQuery Anti-Patterns for Performance
jQuery Anti-Patterns for Performance & Compression
Test Infected Presentation
Jggug 2010 330 Grails 1.3 観察
JSConf: All You Can Leet
Ten useful JavaScript tips & best practices
Secrets of JavaScript Libraries
JAVA...With N.E.T_B.E.A.N.S___________________________________.pdf
Implement threads and a GUI interface using advanced Java Swing clas.pdf
Integration Project Inspection 3
Android workshop
Ad

Recently uploaded (20)

PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
NewMind AI Monthly Chronicles - July 2025
PPTX
Big Data Technologies - Introduction.pptx
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
Cloud computing and distributed systems.
DOCX
The AUB Centre for AI in Media Proposal.docx
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Modernizing your data center with Dell and AMD
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Per capita expenditure prediction using model stacking based on satellite ima...
Mobile App Security Testing_ A Comprehensive Guide.pdf
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Spectral efficient network and resource selection model in 5G networks
Building Integrated photovoltaic BIPV_UPV.pdf
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
CIFDAQ's Market Insight: SEC Turns Pro Crypto
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Encapsulation_ Review paper, used for researhc scholars
Dropbox Q2 2025 Financial Results & Investor Presentation
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
NewMind AI Monthly Chronicles - July 2025
Big Data Technologies - Introduction.pptx
Advanced methodologies resolving dimensionality complications for autism neur...
Cloud computing and distributed systems.
The AUB Centre for AI in Media Proposal.docx
Understanding_Digital_Forensics_Presentation.pptx
Modernizing your data center with Dell and AMD
20250228 LYD VKU AI Blended-Learning.pptx

FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End Developers