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.
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.
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__
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
🎉
it('should return true when tickets are available', () => {
		 const testMovie = {
		 ticketsRemaining: 27,
		 };
		 const result = app.ticketsLeft(testMovie);
		 const expected = true;
		
		 expect(result).toEqual(expected);
		});
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);
		 });
		 });
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`;
		 }, '');
		}
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);
		
		 });
		 });
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);
		
		 });
		 });
other matchers.
toBeNull, toBeUndefined, toBeDefined, toBeTruthy,
toBeFalsy, toBeGreaterThan, toBeGreaterThanOrEqual,
toBeLessThan, toMatch, toContain ...
all done! i think?
let’s setup some code coverage!
update our test script.
"scripts": {
"test": "jest --coverage"
}
buyTickets()
add a watcher for continuous testing runs.
"scripts": {
"test": "jest --coverage --watch"
}
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

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