SlideShare a Scribd company logo
1 of 71
Download to read offline
Unit Testing
The Whys, Whens and Hows
Ates Goral - Toronto Node.js Meetup - October 11, 2016
Ates Goral
@atesgoral
http://magnetiq.com
http://github.com/atesgoral
http://stackoverflow.com/users/23501/ates-goral
http://myplanet.com
Definition of a unit test
What is a unit?
● Smallest bit of code you can test?
● Talking to the actual resource may be OK if it’s stable and fast
● Classic versus mockist styles (Martin Fowler)
● Solitary versus sociable tests (Jay Fields)
● White box versus black box testing
● What’s important is the contract
http://martinfowler.com/bliki/UnitTest.html
Inconsistent definitions
Here’s what’s common:
● Written by developers
● Runs fast
● Deterministic
● Does not tread into integration test territory
Appreciation of unit testing
You don’t know unit testing until you’ve unit tested
There’s a first time for every developer. Some are more lucky than others because
they ramp up in an environment that already embraces unit testing.
“But can already write flawless code when I’m in the zone.”
True. Because you’re actually running unit tests, without realizing, in your mind
when you’re in the zone.
Try taking a 3 week break and see what happens to those ephemeral unit tests.
Turn those tests into unit test code so that they’re repeatable and unforgettable.
Good unit tests
Good unit tests
● Are functionally correct. They don’t just exercise code for the sake of
exercising code.
● Don’t depend on subsequent tests -- every test runs in its own clean
environment, failure of a test doesn’t bring the entire test suite down
● Run fast. You need to be able to run all of your tests as quickly and as
frequently as possible. Otherwise, they lose value.
● Are actually run. Automatically. So that you don’t forget to run them.
● Add new unit tests for newly discovered [and fixed] issues.
Good code
Good code
● Good code is more unit testable
● It all comes down to good architecture and design
● Planning for unit tests facilitates good code
● Good encapsulation: interfaces with small surfaces, well-defined contracts,
non-leaky abstractions
● Keep interdependencies low
Good reasons
Why and what are you unit testing?
● Misguided reasons: processes, meeting performance numbers
● Testing just for testing: glue code that doesn’t have any logic, ineffective tests
that don’t actually test the functionality
● Testing legacy code that is actually un-unit-testable
Be pragmatic. Don’t waste effort. Sometimes unit testing is not the answer (try
end-to-end instead).
Benefits of unit testing
Benefits of unit testing
Benefits beyond finding bugs:
● Better code
● Safety net for refactoring
● Documentation of functionality (especially when in BDD style)
● Prevents code from becoming an untestable entangled mass
Test-environment-first Programming
Be test-ready on day one
● Even if you’re not planning to add test yet
● Even if there’s no code worth testing yet
● Prime your environment for future unit tests
● Especially, CI environment setup can be time consuming
● You never know when that moment will come when you have some critical
code that needs unit testing
Do this. Please.
Sidenote: At a bare minimum...
Even you have no time or energy to write unit tests as you go, prepare a manual
test plan, and someone in your team execute them (manually) prior to releases.
Bonus: share the effort as a team.
Basic smoke tests, checking for end-to-end sanity and regression.
Do this. Please.
Basic test environment setup
Setting up Mocha - no configuration needed
test/testNothing.js:
describe('nothing', () => {
it('should do nothing', (done) => {
done();
});
});
package.json:
"scripts": {
"test": "mocha"
},
https://mochajs.org/
npm install --save-dev mocha
npm test
nothing
✓ should do nothing
1 passing (8ms)
Adding Chai
test/testExpectation.js:
const chai = require('chai');
const expect = chai.expect;
describe('2 + 2', () => {
it('should equal 4', () => {
expect(2 + 2).to.equal(4);
});
});
http://chaijs.com/
npm install --save-dev chai
npm test
2 + 2
✓ should equal 4
Let’s write our first proper test
The test
test/testArithmetic.js:
const arithmetic = require('../src/arithmetic');
describe('arithmetic', () => {
describe('.sum()', () => {
describe('when called with two numbers', () => {
it('should return their sum', () => {
expect(arithmetic.sum(2, 2)).to.equal(4);
});
});
});
});
Implementation and run
src/arithmetic.js:
*** REDACTED ***
npm test
arithmetic
.sum()
when called with two numbers
✓ should return their sum
Opportunistic implementation
src/arithmetic.js:
exports.sum = (a, b) => {
return 4;
};
https://xkcd.com/221/
Who tests the tests?
Test correctness
● Should not be just exercising code
● Should be functionally correct
● Subject to peer review?
I don’t know of any solutions to ensure test correctness.
OH BTW
Selectively running tests with Mocha
mocha --grep <pattern>
npm test -- --grep <pattern>
e.g.
npm test -- --grep arithmetic
Let’s get asynchronous
Timeout implementation
src/timeout.js:
exports.set = (callback, milliseconds) => {
setTimeout(callback, milliseconds);
};
Timeout test
test/testTimeout.js:
it('should call the callback after the delay', (done) => {
const start = Date.now();
timeout.set(() => {
const elapsed = Date.now() - start;
expect(elapsed).to.equal(100);
done();
}, 100);
});
Run
npm test
timeout
.set()
when called with a callback and a delay
1) should call the callback after the delay
Uncaught AssertionError: expected 105 to equal 100
+ expected - actual
-105
+100
Flaky tests are evil
Write deterministic tests that run fast
● Don’t rely on chance
● A less than 100% pass rate is not acceptable
● Don’t waste time with arbitrary delays
● Use the right tools for the [right] job
Deterministic timing
Bring in Sinon
http://sinonjs.org/
npm install --save-dev sinon
Use a spy and a fake timer
test/testTimeout.js:
const sinon = require('sinon');
describe('timeout', () => {
let clock = null;
beforeEach(() => {
clock = sinon.useFakeTimers();
});
afterEach(() => {
clock.restore();
});
Use a spy and a fake timer (continued)
describe('.set()', () => {
describe('when called with a callback and a delay', () => {
it('should call the callback after the delay', () => {
const callback = sinon.spy();
timeout.set(callback, 100);
clock.tick(100);
expect(callback).to.have.been.called;
});
});
});
Run
npm test -- --grep timeout
timeout
.set()
when called with a callback and a delay
✓ should call the callback after the delay
100% pass rate.
Definitions of test doubles
Again, some inconsistencies
● Dummy
● Fake
● Stub
● Spy
● Mock
http://www.martinfowler.com/bliki/TestDouble.html
https://en.wikipedia.org/wiki/Test_double
Test doubles - dependency injection
Account service that takes DB as a dependency
src/accountService.js:
function AccountService(db) {
this.db = db;
}
AccountService.prototype.findById = function (accountId, callback) {
const results = this.db.querySync('account', { id: accountId });
callback(results[0]);
};
module.exports = AccountService;
Bring in Sinon-Chai
https://github.com/domenic/sinon-chai
npm install --save-dev sinon-chai
const sinonChai = require('sinon-chai');
chai.use(sinonChai);
Account service test
test/testAccountService.js:
describe('AccountService', () => {
let db = null;
let accountService = null;
beforeEach(() => {
db = {
querySync: sinon.stub()
};
accountService = new AccountService(db);
});
Account service test (continued)
db.querySync.withArgs('account', { id: 1 }).returns([{
id: 1,
name: 'John Doe'
}]);
const callback = sinon.spy();
accountService.findById(1, callback);
expect(callback).to.have.been.calledWith({
id: 1,
name: 'John Doe'
});
Promises
DB now uses promises
src/accountService.js:
function AccountService(db) {
this.db = db;
}
AccountService.prototype.findById = function (accountId, callback) {
return this.db
.query('account', { id: accountId })
.then((results) => results[0]);
};
module.exports = AccountService;
Bring in sinon-as-promised
https://www.npmjs.com/package/sinon-as-promised
npm install --save-dev sinon-as-promised
const sinonAsPromised = require('sinon-as-promised');
Updated account service test
beforeEach(() => {
db = {
query: sinon.stub()
};
accountService = new AccountService(db);
});
Updated account service test (continued)
db.query.withArgs('account', { id: 1 }).resolves([{
id: 1,
name: 'John Doe'
}]);
return accountService.findById(1)
.then((account) => {
expect(account).to.deep.equal({
id: 1,
name: 'John Doe'
});
});
Negative case
When account not found
db.query.withArgs('account', { id: -1 }).rejects(
new Error('Account not found')
);
return accountService.findById(-1)
.catch((error) => {
expect(error).to.deep.equal(
new Error('Account not found')
);
});
But wait...
src/accountService.js:
AccountService.prototype.findById = function (accountId, callback) {
if (accountId === -1) {
return Promise.resolve({
id: -1,
name: 'Negative One'
});
}
return this.db
.query('account', { id: accountId })
.then((results) => results[0]);
};
Run
npm test -- --grep account
AccountService
.findById()
when called for an existing account
✓ should return a promise resolved with the account
when called for a non-existent account
✓ should return a promise rejected with an error
Need the positive case to fail the test
return accountService.findById(-1)
.catch((error) => {
expect(error).to.deep.equal(
new Error('Account not found')
);
})
.then(() => {
throw new Error('Should not have been resolved');
});
Run
npm test -- --grep account
AccountService
.findById()
when called for an existing account
✓ should return a promise resolved with the account
when called for a non-existent account
1) should return a promise rejected with an error
Making the experience better
Bring in Chai as Promised
http://chaijs.com/plugins/chai-as-promised/
npm install --save-dev chai-as-promised
const chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
Updated positive test
return expect(accountService.findById(1))
.to.eventually.deep.equal({
id: 1,
name: 'John Doe'
});
Updated negative test
return expect(accountService.findById(-1))
.to.eventually.be.rejectedWith(Error, 'Account not found');
Run
npm test -- --grep account
AccountService
.findById()
when called for an existing account
✓ should return a promise resolved with the account
when called for a non-existent account
1) should return a promise rejected with an error
AssertionError:
expected promise to be rejected with 'Error'
but it was fulfilled with { id: -1, name: 'Negative One' }
Without dependency injection
To intercept any module dependency - Mockery
https://github.com/mfncooper/mockery
npm install --save-dev mockery
beforeEach(() => {
mockery.enable({
warnOnReplace: false,
warnOnUnregistered: false,
useCleanCache: true
});
mockery.registerMock('./db', db);
});
afterEach(() => {
mockery.disable();
});
All code so far
https://github.com/atesgoral/hello-test
Clean commit history with 1 commit per example.
Q&A

More Related Content

What's hot

BDD Testing and Automating from the trenches - Presented at Into The Box June...
BDD Testing and Automating from the trenches - Presented at Into The Box June...BDD Testing and Automating from the trenches - Presented at Into The Box June...
BDD Testing and Automating from the trenches - Presented at Into The Box June...Gavin Pickin
 
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
[Webinar] Qt Test-Driven Development Using Google Test and Google MockICS
 
Token Testing Slides
Token  Testing SlidesToken  Testing Slides
Token Testing Slidesericholscher
 
(automatic) Testing: from business to university and back
(automatic) Testing: from business to university and back(automatic) Testing: from business to university and back
(automatic) Testing: from business to university and backDavid Rodenas
 
"How keep normal blood pressure using TDD" By Roman Loparev
"How keep normal blood pressure using TDD" By Roman Loparev"How keep normal blood pressure using TDD" By Roman Loparev
"How keep normal blood pressure using TDD" By Roman LoparevCiklum Ukraine
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummiesHarry Potter
 
Intro to TDD and BDD
Intro to TDD and BDDIntro to TDD and BDD
Intro to TDD and BDDJason Noble
 
Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++Hong Le Van
 
Testing in-python-and-pytest-framework
Testing in-python-and-pytest-frameworkTesting in-python-and-pytest-framework
Testing in-python-and-pytest-frameworkArulalan T
 
iOS Unit Testing
iOS Unit TestingiOS Unit Testing
iOS Unit Testingsgleadow
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testingpleeps
 
Java Testing With Spock - Ken Sipe (Trexin Consulting)
Java Testing With Spock - Ken Sipe (Trexin Consulting)Java Testing With Spock - Ken Sipe (Trexin Consulting)
Java Testing With Spock - Ken Sipe (Trexin Consulting)jaxLondonConference
 
JAVASCRIPT Test Driven Development & Jasmine
JAVASCRIPT Test Driven Development & JasmineJAVASCRIPT Test Driven Development & Jasmine
JAVASCRIPT Test Driven Development & JasmineAnup Singh
 
Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)vilniusjug
 

What's hot (18)

BDD Testing and Automating from the trenches - Presented at Into The Box June...
BDD Testing and Automating from the trenches - Presented at Into The Box June...BDD Testing and Automating from the trenches - Presented at Into The Box June...
BDD Testing and Automating from the trenches - Presented at Into The Box June...
 
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
 
Django Testing
Django TestingDjango Testing
Django Testing
 
Token Testing Slides
Token  Testing SlidesToken  Testing Slides
Token Testing Slides
 
(automatic) Testing: from business to university and back
(automatic) Testing: from business to university and back(automatic) Testing: from business to university and back
(automatic) Testing: from business to university and back
 
"How keep normal blood pressure using TDD" By Roman Loparev
"How keep normal blood pressure using TDD" By Roman Loparev"How keep normal blood pressure using TDD" By Roman Loparev
"How keep normal blood pressure using TDD" By Roman Loparev
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummies
 
Intro to TDD and BDD
Intro to TDD and BDDIntro to TDD and BDD
Intro to TDD and BDD
 
Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++
 
Testing in-python-and-pytest-framework
Testing in-python-and-pytest-frameworkTesting in-python-and-pytest-framework
Testing in-python-and-pytest-framework
 
TDD, BDD and mocks
TDD, BDD and mocksTDD, BDD and mocks
TDD, BDD and mocks
 
iOS Unit Testing
iOS Unit TestingiOS Unit Testing
iOS Unit Testing
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testing
 
Java Testing With Spock - Ken Sipe (Trexin Consulting)
Java Testing With Spock - Ken Sipe (Trexin Consulting)Java Testing With Spock - Ken Sipe (Trexin Consulting)
Java Testing With Spock - Ken Sipe (Trexin Consulting)
 
JAVASCRIPT Test Driven Development & Jasmine
JAVASCRIPT Test Driven Development & JasmineJAVASCRIPT Test Driven Development & Jasmine
JAVASCRIPT Test Driven Development & Jasmine
 
ES3-2020-05 Testing
ES3-2020-05 TestingES3-2020-05 Testing
ES3-2020-05 Testing
 
Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)
 
Javascript Unit Testing
Javascript Unit TestingJavascript Unit Testing
Javascript Unit Testing
 

Viewers also liked

和菓子の持つ伝統要素の尊重をしつつ、抜本的なイメージの改変を目指す。
和菓子の持つ伝統要素の尊重をしつつ、抜本的なイメージの改変を目指す。和菓子の持つ伝統要素の尊重をしつつ、抜本的なイメージの改変を目指す。
和菓子の持つ伝統要素の尊重をしつつ、抜本的なイメージの改変を目指す。stucon
 
Moving the Needle with Social Media
Moving the Needle with Social MediaMoving the Needle with Social Media
Moving the Needle with Social MediaStrongView
 
Shodh yatra report compressed copy
Shodh yatra report compressed copyShodh yatra report compressed copy
Shodh yatra report compressed copyMarianne Esders
 
如何讓顧客離不開你
如何讓顧客離不開你如何讓顧客離不開你
如何讓顧客離不開你kkjjkevin03
 
Blue moon - abstract acrylic painting
Blue moon - abstract acrylic paintingBlue moon - abstract acrylic painting
Blue moon - abstract acrylic paintingTataro
 
Risk based monitoring presentation by triumph research intelligence january 2014
Risk based monitoring presentation by triumph research intelligence january 2014Risk based monitoring presentation by triumph research intelligence january 2014
Risk based monitoring presentation by triumph research intelligence january 2014Triumph Consultancy Services
 
Emailer Generic letter
Emailer Generic letterEmailer Generic letter
Emailer Generic letterShane Thompson
 
Relaciones absolu8tas, relativas y mixtas
Relaciones absolu8tas, relativas y mixtasRelaciones absolu8tas, relativas y mixtas
Relaciones absolu8tas, relativas y mixtaspiioJo
 
Token statt Cookies dank JWT - #ETKA16
Token statt Cookies dank JWT - #ETKA16Token statt Cookies dank JWT - #ETKA16
Token statt Cookies dank JWT - #ETKA16Markus Schlichting
 
Social Media for Travel and Tourism
Social Media for Travel and Tourism Social Media for Travel and Tourism
Social Media for Travel and Tourism Ben Shipley
 
Data Defeats Truman – SXSW Panelpicker Pitch
Data Defeats Truman – SXSW Panelpicker PitchData Defeats Truman – SXSW Panelpicker Pitch
Data Defeats Truman – SXSW Panelpicker PitchKyle J. Britt
 
London devops - orc
London devops - orcLondon devops - orc
London devops - orcTomas Doran
 
85 Gnarly Local SEO Tips for Auto Dealers
85 Gnarly Local SEO Tips for Auto Dealers85 Gnarly Local SEO Tips for Auto Dealers
85 Gnarly Local SEO Tips for Auto DealersGreg Gifford
 
UNISA InfoLit Story 24 May 2016
UNISA InfoLit Story 24 May 2016UNISA InfoLit Story 24 May 2016
UNISA InfoLit Story 24 May 2016HELIGLIASA
 
Mattawa, Ontario, Canada, 1970
Mattawa, Ontario, Canada, 1970Mattawa, Ontario, Canada, 1970
Mattawa, Ontario, Canada, 1970Joe Carter
 

Viewers also liked (17)

和菓子の持つ伝統要素の尊重をしつつ、抜本的なイメージの改変を目指す。
和菓子の持つ伝統要素の尊重をしつつ、抜本的なイメージの改変を目指す。和菓子の持つ伝統要素の尊重をしつつ、抜本的なイメージの改変を目指す。
和菓子の持つ伝統要素の尊重をしつつ、抜本的なイメージの改変を目指す。
 
Productos químicos de alta calidad Ronald Vera
Productos químicos de alta calidad Ronald Vera Productos químicos de alta calidad Ronald Vera
Productos químicos de alta calidad Ronald Vera
 
Moving the Needle with Social Media
Moving the Needle with Social MediaMoving the Needle with Social Media
Moving the Needle with Social Media
 
Reda
RedaReda
Reda
 
Shodh yatra report compressed copy
Shodh yatra report compressed copyShodh yatra report compressed copy
Shodh yatra report compressed copy
 
如何讓顧客離不開你
如何讓顧客離不開你如何讓顧客離不開你
如何讓顧客離不開你
 
Blue moon - abstract acrylic painting
Blue moon - abstract acrylic paintingBlue moon - abstract acrylic painting
Blue moon - abstract acrylic painting
 
Risk based monitoring presentation by triumph research intelligence january 2014
Risk based monitoring presentation by triumph research intelligence january 2014Risk based monitoring presentation by triumph research intelligence january 2014
Risk based monitoring presentation by triumph research intelligence january 2014
 
Emailer Generic letter
Emailer Generic letterEmailer Generic letter
Emailer Generic letter
 
Relaciones absolu8tas, relativas y mixtas
Relaciones absolu8tas, relativas y mixtasRelaciones absolu8tas, relativas y mixtas
Relaciones absolu8tas, relativas y mixtas
 
Token statt Cookies dank JWT - #ETKA16
Token statt Cookies dank JWT - #ETKA16Token statt Cookies dank JWT - #ETKA16
Token statt Cookies dank JWT - #ETKA16
 
Social Media for Travel and Tourism
Social Media for Travel and Tourism Social Media for Travel and Tourism
Social Media for Travel and Tourism
 
Data Defeats Truman – SXSW Panelpicker Pitch
Data Defeats Truman – SXSW Panelpicker PitchData Defeats Truman – SXSW Panelpicker Pitch
Data Defeats Truman – SXSW Panelpicker Pitch
 
London devops - orc
London devops - orcLondon devops - orc
London devops - orc
 
85 Gnarly Local SEO Tips for Auto Dealers
85 Gnarly Local SEO Tips for Auto Dealers85 Gnarly Local SEO Tips for Auto Dealers
85 Gnarly Local SEO Tips for Auto Dealers
 
UNISA InfoLit Story 24 May 2016
UNISA InfoLit Story 24 May 2016UNISA InfoLit Story 24 May 2016
UNISA InfoLit Story 24 May 2016
 
Mattawa, Ontario, Canada, 1970
Mattawa, Ontario, Canada, 1970Mattawa, Ontario, Canada, 1970
Mattawa, Ontario, Canada, 1970
 

Similar to Unit Testing - The Whys, Whens and Hows

North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017
North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017
North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017Ortus Solutions, Corp
 
Testing Django Applications
Testing Django ApplicationsTesting Django Applications
Testing Django ApplicationsHonza Král
 
Developer Test - Things to Know
Developer Test - Things to KnowDeveloper Test - Things to Know
Developer Test - Things to Knowvilniusjug
 
A la découverte des google/test (aka gtest)
A la découverte des google/test (aka gtest)A la découverte des google/test (aka gtest)
A la découverte des google/test (aka gtest)Thierry Gayet
 
Jest: Frontend Testing leicht gemacht @EnterJS2018
Jest: Frontend Testing leicht gemacht @EnterJS2018Jest: Frontend Testing leicht gemacht @EnterJS2018
Jest: Frontend Testing leicht gemacht @EnterJS2018Holger Grosse-Plankermann
 
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 DevelopmentAll Things Open
 
Google test training
Google test trainingGoogle test training
Google test trainingThierry Gayet
 
unit test in node js - test cases in node
unit test in node js - test cases in nodeunit test in node js - test cases in node
unit test in node js - test cases in nodeGoa App
 
Test and Behaviour Driven Development (TDD/BDD)
Test and Behaviour Driven Development (TDD/BDD)Test and Behaviour Driven Development (TDD/BDD)
Test and Behaviour Driven Development (TDD/BDD)Lars Thorup
 
Das Frontend richtig Testen – mit Jest @Developer Week 2018
Das Frontend richtig Testen – mit Jest @Developer Week 2018Das Frontend richtig Testen – mit Jest @Developer Week 2018
Das Frontend richtig Testen – mit Jest @Developer Week 2018Holger Grosse-Plankermann
 
Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013Dror Helper
 
Writing Tests with the Unity Test Framework
Writing Tests with the Unity Test FrameworkWriting Tests with the Unity Test Framework
Writing Tests with the Unity Test FrameworkPeter Kofler
 
Unit testing with Spock Framework
Unit testing with Spock FrameworkUnit testing with Spock Framework
Unit testing with Spock FrameworkEugene Dvorkin
 
Test-Driven Development In Action
Test-Driven Development In ActionTest-Driven Development In Action
Test-Driven Development In ActionJon Kruger
 
Test driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + EclipseTest driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + EclipseUTC Fire & Security
 
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit TutorialJAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit TutorialAnup Singh
 
Java script unit testing
Java script unit testingJava script unit testing
Java script unit testingMats Bryntse
 
Developers Testing - Girl Code at bloomon
Developers Testing - Girl Code at bloomonDevelopers Testing - Girl Code at bloomon
Developers Testing - Girl Code at bloomonIneke Scheffers
 

Similar to Unit Testing - The Whys, Whens and Hows (20)

North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017
North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017
North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017
 
Testing Django Applications
Testing Django ApplicationsTesting Django Applications
Testing Django Applications
 
Developer Test - Things to Know
Developer Test - Things to KnowDeveloper Test - Things to Know
Developer Test - Things to Know
 
Test Driven
Test DrivenTest Driven
Test Driven
 
A la découverte des google/test (aka gtest)
A la découverte des google/test (aka gtest)A la découverte des google/test (aka gtest)
A la découverte des google/test (aka gtest)
 
Jest: Frontend Testing leicht gemacht @EnterJS2018
Jest: Frontend Testing leicht gemacht @EnterJS2018Jest: Frontend Testing leicht gemacht @EnterJS2018
Jest: Frontend Testing leicht gemacht @EnterJS2018
 
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
 
Google test training
Google test trainingGoogle test training
Google test training
 
unit test in node js - test cases in node
unit test in node js - test cases in nodeunit test in node js - test cases in node
unit test in node js - test cases in node
 
Test and Behaviour Driven Development (TDD/BDD)
Test and Behaviour Driven Development (TDD/BDD)Test and Behaviour Driven Development (TDD/BDD)
Test and Behaviour Driven Development (TDD/BDD)
 
Das Frontend richtig Testen – mit Jest @Developer Week 2018
Das Frontend richtig Testen – mit Jest @Developer Week 2018Das Frontend richtig Testen – mit Jest @Developer Week 2018
Das Frontend richtig Testen – mit Jest @Developer Week 2018
 
Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013
 
Writing Tests with the Unity Test Framework
Writing Tests with the Unity Test FrameworkWriting Tests with the Unity Test Framework
Writing Tests with the Unity Test Framework
 
Unit testing with Spock Framework
Unit testing with Spock FrameworkUnit testing with Spock Framework
Unit testing with Spock Framework
 
Test-Driven Development In Action
Test-Driven Development In ActionTest-Driven Development In Action
Test-Driven Development In Action
 
Full Stack Unit Testing
Full Stack Unit TestingFull Stack Unit Testing
Full Stack Unit Testing
 
Test driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + EclipseTest driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + Eclipse
 
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit TutorialJAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
 
Java script unit testing
Java script unit testingJava script unit testing
Java script unit testing
 
Developers Testing - Girl Code at bloomon
Developers Testing - Girl Code at bloomonDevelopers Testing - Girl Code at bloomon
Developers Testing - Girl Code at bloomon
 

Recently uploaded

Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
How To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROHow To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROmotivationalword821
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 

Recently uploaded (20)

Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
How To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROHow To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTRO
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 

Unit Testing - The Whys, Whens and Hows

  • 1. Unit Testing The Whys, Whens and Hows Ates Goral - Toronto Node.js Meetup - October 11, 2016
  • 4. Definition of a unit test
  • 5. What is a unit? ● Smallest bit of code you can test? ● Talking to the actual resource may be OK if it’s stable and fast ● Classic versus mockist styles (Martin Fowler) ● Solitary versus sociable tests (Jay Fields) ● White box versus black box testing ● What’s important is the contract http://martinfowler.com/bliki/UnitTest.html
  • 6. Inconsistent definitions Here’s what’s common: ● Written by developers ● Runs fast ● Deterministic ● Does not tread into integration test territory
  • 8. You don’t know unit testing until you’ve unit tested There’s a first time for every developer. Some are more lucky than others because they ramp up in an environment that already embraces unit testing. “But can already write flawless code when I’m in the zone.” True. Because you’re actually running unit tests, without realizing, in your mind when you’re in the zone. Try taking a 3 week break and see what happens to those ephemeral unit tests. Turn those tests into unit test code so that they’re repeatable and unforgettable.
  • 10. Good unit tests ● Are functionally correct. They don’t just exercise code for the sake of exercising code. ● Don’t depend on subsequent tests -- every test runs in its own clean environment, failure of a test doesn’t bring the entire test suite down ● Run fast. You need to be able to run all of your tests as quickly and as frequently as possible. Otherwise, they lose value. ● Are actually run. Automatically. So that you don’t forget to run them. ● Add new unit tests for newly discovered [and fixed] issues.
  • 12. Good code ● Good code is more unit testable ● It all comes down to good architecture and design ● Planning for unit tests facilitates good code ● Good encapsulation: interfaces with small surfaces, well-defined contracts, non-leaky abstractions ● Keep interdependencies low
  • 14. Why and what are you unit testing? ● Misguided reasons: processes, meeting performance numbers ● Testing just for testing: glue code that doesn’t have any logic, ineffective tests that don’t actually test the functionality ● Testing legacy code that is actually un-unit-testable Be pragmatic. Don’t waste effort. Sometimes unit testing is not the answer (try end-to-end instead).
  • 15. Benefits of unit testing
  • 16. Benefits of unit testing Benefits beyond finding bugs: ● Better code ● Safety net for refactoring ● Documentation of functionality (especially when in BDD style) ● Prevents code from becoming an untestable entangled mass
  • 18. Be test-ready on day one ● Even if you’re not planning to add test yet ● Even if there’s no code worth testing yet ● Prime your environment for future unit tests ● Especially, CI environment setup can be time consuming ● You never know when that moment will come when you have some critical code that needs unit testing Do this. Please.
  • 19. Sidenote: At a bare minimum... Even you have no time or energy to write unit tests as you go, prepare a manual test plan, and someone in your team execute them (manually) prior to releases. Bonus: share the effort as a team. Basic smoke tests, checking for end-to-end sanity and regression. Do this. Please.
  • 21. Setting up Mocha - no configuration needed test/testNothing.js: describe('nothing', () => { it('should do nothing', (done) => { done(); }); }); package.json: "scripts": { "test": "mocha" }, https://mochajs.org/ npm install --save-dev mocha npm test nothing ✓ should do nothing 1 passing (8ms)
  • 22. Adding Chai test/testExpectation.js: const chai = require('chai'); const expect = chai.expect; describe('2 + 2', () => { it('should equal 4', () => { expect(2 + 2).to.equal(4); }); }); http://chaijs.com/ npm install --save-dev chai npm test 2 + 2 ✓ should equal 4
  • 23. Let’s write our first proper test
  • 24. The test test/testArithmetic.js: const arithmetic = require('../src/arithmetic'); describe('arithmetic', () => { describe('.sum()', () => { describe('when called with two numbers', () => { it('should return their sum', () => { expect(arithmetic.sum(2, 2)).to.equal(4); }); }); }); });
  • 25. Implementation and run src/arithmetic.js: *** REDACTED *** npm test arithmetic .sum() when called with two numbers ✓ should return their sum
  • 28.
  • 29. Who tests the tests?
  • 30. Test correctness ● Should not be just exercising code ● Should be functionally correct ● Subject to peer review? I don’t know of any solutions to ensure test correctness.
  • 32. Selectively running tests with Mocha mocha --grep <pattern> npm test -- --grep <pattern> e.g. npm test -- --grep arithmetic
  • 34. Timeout implementation src/timeout.js: exports.set = (callback, milliseconds) => { setTimeout(callback, milliseconds); };
  • 35. Timeout test test/testTimeout.js: it('should call the callback after the delay', (done) => { const start = Date.now(); timeout.set(() => { const elapsed = Date.now() - start; expect(elapsed).to.equal(100); done(); }, 100); });
  • 36. Run npm test timeout .set() when called with a callback and a delay 1) should call the callback after the delay Uncaught AssertionError: expected 105 to equal 100 + expected - actual -105 +100
  • 38. Write deterministic tests that run fast ● Don’t rely on chance ● A less than 100% pass rate is not acceptable ● Don’t waste time with arbitrary delays ● Use the right tools for the [right] job
  • 40. Bring in Sinon http://sinonjs.org/ npm install --save-dev sinon
  • 41. Use a spy and a fake timer test/testTimeout.js: const sinon = require('sinon'); describe('timeout', () => { let clock = null; beforeEach(() => { clock = sinon.useFakeTimers(); }); afterEach(() => { clock.restore(); });
  • 42. Use a spy and a fake timer (continued) describe('.set()', () => { describe('when called with a callback and a delay', () => { it('should call the callback after the delay', () => { const callback = sinon.spy(); timeout.set(callback, 100); clock.tick(100); expect(callback).to.have.been.called; }); }); });
  • 43. Run npm test -- --grep timeout timeout .set() when called with a callback and a delay ✓ should call the callback after the delay 100% pass rate.
  • 45.
  • 46. Again, some inconsistencies ● Dummy ● Fake ● Stub ● Spy ● Mock http://www.martinfowler.com/bliki/TestDouble.html https://en.wikipedia.org/wiki/Test_double
  • 47. Test doubles - dependency injection
  • 48. Account service that takes DB as a dependency src/accountService.js: function AccountService(db) { this.db = db; } AccountService.prototype.findById = function (accountId, callback) { const results = this.db.querySync('account', { id: accountId }); callback(results[0]); }; module.exports = AccountService;
  • 49. Bring in Sinon-Chai https://github.com/domenic/sinon-chai npm install --save-dev sinon-chai const sinonChai = require('sinon-chai'); chai.use(sinonChai);
  • 50. Account service test test/testAccountService.js: describe('AccountService', () => { let db = null; let accountService = null; beforeEach(() => { db = { querySync: sinon.stub() }; accountService = new AccountService(db); });
  • 51. Account service test (continued) db.querySync.withArgs('account', { id: 1 }).returns([{ id: 1, name: 'John Doe' }]); const callback = sinon.spy(); accountService.findById(1, callback); expect(callback).to.have.been.calledWith({ id: 1, name: 'John Doe' });
  • 53. DB now uses promises src/accountService.js: function AccountService(db) { this.db = db; } AccountService.prototype.findById = function (accountId, callback) { return this.db .query('account', { id: accountId }) .then((results) => results[0]); }; module.exports = AccountService;
  • 54. Bring in sinon-as-promised https://www.npmjs.com/package/sinon-as-promised npm install --save-dev sinon-as-promised const sinonAsPromised = require('sinon-as-promised');
  • 55. Updated account service test beforeEach(() => { db = { query: sinon.stub() }; accountService = new AccountService(db); });
  • 56. Updated account service test (continued) db.query.withArgs('account', { id: 1 }).resolves([{ id: 1, name: 'John Doe' }]); return accountService.findById(1) .then((account) => { expect(account).to.deep.equal({ id: 1, name: 'John Doe' }); });
  • 58. When account not found db.query.withArgs('account', { id: -1 }).rejects( new Error('Account not found') ); return accountService.findById(-1) .catch((error) => { expect(error).to.deep.equal( new Error('Account not found') ); });
  • 59. But wait... src/accountService.js: AccountService.prototype.findById = function (accountId, callback) { if (accountId === -1) { return Promise.resolve({ id: -1, name: 'Negative One' }); } return this.db .query('account', { id: accountId }) .then((results) => results[0]); };
  • 60. Run npm test -- --grep account AccountService .findById() when called for an existing account ✓ should return a promise resolved with the account when called for a non-existent account ✓ should return a promise rejected with an error
  • 61. Need the positive case to fail the test return accountService.findById(-1) .catch((error) => { expect(error).to.deep.equal( new Error('Account not found') ); }) .then(() => { throw new Error('Should not have been resolved'); });
  • 62. Run npm test -- --grep account AccountService .findById() when called for an existing account ✓ should return a promise resolved with the account when called for a non-existent account 1) should return a promise rejected with an error
  • 64. Bring in Chai as Promised http://chaijs.com/plugins/chai-as-promised/ npm install --save-dev chai-as-promised const chaiAsPromised = require('chai-as-promised'); chai.use(chaiAsPromised);
  • 65. Updated positive test return expect(accountService.findById(1)) .to.eventually.deep.equal({ id: 1, name: 'John Doe' });
  • 66. Updated negative test return expect(accountService.findById(-1)) .to.eventually.be.rejectedWith(Error, 'Account not found');
  • 67. Run npm test -- --grep account AccountService .findById() when called for an existing account ✓ should return a promise resolved with the account when called for a non-existent account 1) should return a promise rejected with an error AssertionError: expected promise to be rejected with 'Error' but it was fulfilled with { id: -1, name: 'Negative One' }
  • 69. To intercept any module dependency - Mockery https://github.com/mfncooper/mockery npm install --save-dev mockery beforeEach(() => { mockery.enable({ warnOnReplace: false, warnOnUnregistered: false, useCleanCache: true }); mockery.registerMock('./db', db); }); afterEach(() => { mockery.disable(); });
  • 70. All code so far https://github.com/atesgoral/hello-test Clean commit history with 1 commit per example.
  • 71. Q&A