SlideShare a Scribd company logo
Async JS Unit Testing
Team: El Pimpi
Mihail Gaberov
Motivation
● To have all team/community members acknowledged in
the field and be able to write unit test for our Javascript
based projects.
● This could be continued as series of internal workshops
in order to keep improving ourselves in all front-end
skills that we need or might need.
What is asynchronous code?
What is an async test?
● Unit tests for asynchronous code, code that returns
promise of something that will happen in the future.
it("Using a Promise with async/await that resolves successfully with wrong
expectation!", async function() {
var testPromise = new Promise(function(resolve, reject) {
setTimeout(function() {
resolve("Hello World!”);
}, 200);
});
var result = await testPromise;
expect(result).to.equal("Hello!");
});
How do we write JS unit tests?
● Callbacks - callbacks hell:
“In a real codebase, each callback
function might be quite long, which
can result in huge and deeply
indented functions. Dealing with
this type of code, working with
callbacks within callbacks within
callbacks, is what is commonly
referred to as "callback hell”."
function callbackHell () {
const api = new Api()
let user, friends
api.getUser().then(function (returnedUser) {
user = returnedUser
api.getFriends(user.id).then(function
(returnedFriends) {
friends = returnedFriends
api.getPhoto(user.id).then(function (photo) {
console.log('callbackHell', { user, friends,
photo })
})
})
})
}
● Promises - they can be chained by returning another promise inside each callback,
this way we can keep all of the callbacks on the same indentation level. We're also
using arrow functions to abbreviate the callback function declarations.
How do we write JS unit tests?
“Promises are a new, built-in type
of object that help you work with
asynchronous code. A promise is a
placeholder for a value that we
don’t have yet but will at some later
point. They’re especially good for
working with multiple asynchronous
steps.”
function promiseChain () {
const api = new Api()
let user, friends
api.getUser()
.then((returnedUser) => {
user = returnedUser
return api.getFriends(user.id)
})
.then((returnedFriends) => {
friends = returnedFriends
return api.getPhoto(user.id)
})
.then((photo) => {
console.log('promiseChain', { user, friends, photo })
})
}
● Generators - Generators are a special type of function. Whereas a standard function 

produces at most a single value while running its code from start to finish, generators

produce multiple values, on a per request basis, while suspending their execution 

between these requests.
How do we write JS unit tests?
“A generator function is defined by
putting an asterisk right after the
function keyword. We can use the
new yield keyword in generator
functions.”
function* WeaponGenerator(){
yield "Katana";
yield "Wakizashi";
yield "Kusarigama";
}
for(let weapon of WeaponGenerator()) {
assert(weapon !== undefined, weapon);
}
or
const weaponsIterator = WeaponGenerator();
const result1 = weaponsIterator.next();
● Promises + Generators = Async await
How do we write JS unit tests?
“We put the code that uses
asynchronous tasks in a generator,
and we execute that generator
function. When we reach a point in
the generator execution that calls
an asynchronous task, we create a
promise that represents the value of
that asynchronous task. Because
we have no idea when that promise
will be resolved (or even if it will be
resolved), at this point of generator
execution, we yield from the
generator, so that we don’t cause
blocking.”
(async function (){
try {
const ninjas = await getJSON("data/ninjas.json");
const missions = await getJSON(missions[0].missionsUrl);
console.log(missions);
}
catch(e) {
console.log("Error: ", e);
}
})()
async(function*() {
try {
const ninjas = yield getJSON("data/ninjas.json");
const missions = yield getJSON(ninjas[0].missionsUrl);
const missionDescription = yield getJSON(missions[0].detailsUrl);
//All information received
}
catch(e) {
//An error has occurred
}
});
● Sinonjs - test spies, stubs and mocks for JS
How do we write JS unit tests?
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);
});
});
Examples
https://github.com/mihailgaberov/javascript-testing
References:
Simplifying Asynchronous Coding with Async Functions
Error handling Promises in JavaScript
Async/Await in JavaScript
Testing Asynchronous Code with MochaJS and ES7 async/await
Testing Asynchronous JavaScript
Async/Await will make your code simpler
Secrets of the JavaScript Ninja

More Related Content

What's hot (20)

Better React state management with Redux
Better React state management with ReduxBetter React state management with Redux
Better React state management with Redux
Maurice De Beijer [MVP]
 
Let's Redux!
Let's Redux!Let's Redux!
Let's Redux!
Joseph Chiang
 
React & Redux
React & ReduxReact & Redux
React & Redux
Federico Bond
 
React Lifecycle and Reconciliation
React Lifecycle and ReconciliationReact Lifecycle and Reconciliation
React Lifecycle and Reconciliation
Zhihao Li
 
Building React Applications with Redux
Building React Applications with ReduxBuilding React Applications with Redux
Building React Applications with Redux
FITC
 
ProvJS: Six Months of ReactJS and Redux
ProvJS:  Six Months of ReactJS and ReduxProvJS:  Six Months of ReactJS and Redux
ProvJS: Six Months of ReactJS and Redux
Thom Nichols
 
React, Redux, ES2015 by Max Petruck
React, Redux, ES2015   by Max PetruckReact, Redux, ES2015   by Max Petruck
React, Redux, ES2015 by Max Petruck
Maksym Petruk
 
React + Redux. Best practices
React + Redux.  Best practicesReact + Redux.  Best practices
React + Redux. Best practices
Clickky
 
Intro to React
Intro to ReactIntro to React
Intro to React
Troy Miles
 
Workshop 17: EmberJS parte II
Workshop 17: EmberJS parte IIWorkshop 17: EmberJS parte II
Workshop 17: EmberJS parte II
Visual Engineering
 
Rethinking Best Practices
Rethinking Best PracticesRethinking Best Practices
Rethinking Best Practices
floydophone
 
React js
React jsReact js
React js
Jai Santhosh
 
Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3 Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3
DreamLab
 
State Models for React with Redux
State Models for React with ReduxState Models for React with Redux
State Models for React with Redux
Stephan Schmidt
 
Angular2 & ngrx/store: Game of States
Angular2 & ngrx/store: Game of StatesAngular2 & ngrx/store: Game of States
Angular2 & ngrx/store: Game of States
Oren Farhi
 
Quick start with React | DreamLab Academy #2
Quick start with React | DreamLab Academy #2Quick start with React | DreamLab Academy #2
Quick start with React | DreamLab Academy #2
DreamLab
 
React for Dummies
React for DummiesReact for Dummies
React for Dummies
Mitch Chen
 
An Introduction to ReactJS
An Introduction to ReactJSAn Introduction to ReactJS
An Introduction to ReactJS
All Things Open
 
React on es6+
React on es6+React on es6+
React on es6+
Nikolaus Graf
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous Javascript
Garrett Welson
 
Better React state management with Redux
Better React state management with ReduxBetter React state management with Redux
Better React state management with Redux
Maurice De Beijer [MVP]
 
React Lifecycle and Reconciliation
React Lifecycle and ReconciliationReact Lifecycle and Reconciliation
React Lifecycle and Reconciliation
Zhihao Li
 
Building React Applications with Redux
Building React Applications with ReduxBuilding React Applications with Redux
Building React Applications with Redux
FITC
 
ProvJS: Six Months of ReactJS and Redux
ProvJS:  Six Months of ReactJS and ReduxProvJS:  Six Months of ReactJS and Redux
ProvJS: Six Months of ReactJS and Redux
Thom Nichols
 
React, Redux, ES2015 by Max Petruck
React, Redux, ES2015   by Max PetruckReact, Redux, ES2015   by Max Petruck
React, Redux, ES2015 by Max Petruck
Maksym Petruk
 
React + Redux. Best practices
React + Redux.  Best practicesReact + Redux.  Best practices
React + Redux. Best practices
Clickky
 
Intro to React
Intro to ReactIntro to React
Intro to React
Troy Miles
 
Rethinking Best Practices
Rethinking Best PracticesRethinking Best Practices
Rethinking Best Practices
floydophone
 
Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3 Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3
DreamLab
 
State Models for React with Redux
State Models for React with ReduxState Models for React with Redux
State Models for React with Redux
Stephan Schmidt
 
Angular2 & ngrx/store: Game of States
Angular2 & ngrx/store: Game of StatesAngular2 & ngrx/store: Game of States
Angular2 & ngrx/store: Game of States
Oren Farhi
 
Quick start with React | DreamLab Academy #2
Quick start with React | DreamLab Academy #2Quick start with React | DreamLab Academy #2
Quick start with React | DreamLab Academy #2
DreamLab
 
React for Dummies
React for DummiesReact for Dummies
React for Dummies
Mitch Chen
 
An Introduction to ReactJS
An Introduction to ReactJSAn Introduction to ReactJS
An Introduction to ReactJS
All Things Open
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous Javascript
Garrett Welson
 

Similar to Async JavaScript Unit Testing (20)

Unit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and HowsUnit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and Hows
atesgoral
 
Unit testing JavaScript using Mocha and Node
Unit testing JavaScript using Mocha and NodeUnit testing JavaScript using Mocha and Node
Unit testing JavaScript using Mocha and Node
Josh Mock
 
Unit tests in node.js
Unit tests in node.jsUnit tests in node.js
Unit tests in node.js
Rotem Tamir
 
Unit-testing and E2E testing in JS
Unit-testing and E2E testing in JSUnit-testing and E2E testing in JS
Unit-testing and E2E testing in JS
Michael Haberman
 
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
Goa App
 
Qunit Java script Un
Qunit Java script UnQunit Java script Un
Qunit Java script Un
akanksha arora
 
Unit Testing JavaScript Applications
Unit Testing JavaScript ApplicationsUnit Testing JavaScript Applications
Unit Testing JavaScript Applications
Ynon Perek
 
Testacular
TestacularTestacular
Testacular
James Ford
 
4 mishchevskii - testing stage18-
4   mishchevskii - testing stage18-4   mishchevskii - testing stage18-
4 mishchevskii - testing stage18-
Ievgenii Katsan
 
Test automation expert days
Test automation   expert daysTest automation   expert days
Test automation expert days
Oren Rubin
 
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
Anup Singh
 
Testing nodejs apps
Testing nodejs appsTesting nodejs apps
Testing nodejs apps
felipefsilva
 
Full Stack Unit Testing
Full Stack Unit TestingFull Stack Unit Testing
Full Stack Unit Testing
GlobalLogic Ukraine
 
Type mock isolator
Type mock isolatorType mock isolator
Type mock isolator
MaslowB
 
Asynchronous development in JavaScript
Asynchronous development  in JavaScriptAsynchronous development  in JavaScript
Asynchronous development in JavaScript
Amitai Barnea
 
Boom! Promises/A+ Was Born
Boom! Promises/A+ Was BornBoom! Promises/A+ Was Born
Boom! Promises/A+ Was Born
Domenic Denicola
 
Angular Unit Testing
Angular Unit TestingAngular Unit Testing
Angular Unit Testing
Alessandro Giorgetti
 
Ecma script
Ecma scriptEcma script
Ecma script
MOHIT KUMAR
 
Avoiding callback hell with promises
Avoiding callback hell with promisesAvoiding callback hell with promises
Avoiding callback hell with promises
TorontoNodeJS
 
Testing in JavaScript - August 2018 - WebElement Bardejov
Testing in JavaScript - August 2018 - WebElement BardejovTesting in JavaScript - August 2018 - WebElement Bardejov
Testing in JavaScript - August 2018 - WebElement Bardejov
Marian Rusnak
 
Unit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and HowsUnit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and Hows
atesgoral
 
Unit testing JavaScript using Mocha and Node
Unit testing JavaScript using Mocha and NodeUnit testing JavaScript using Mocha and Node
Unit testing JavaScript using Mocha and Node
Josh Mock
 
Unit tests in node.js
Unit tests in node.jsUnit tests in node.js
Unit tests in node.js
Rotem Tamir
 
Unit-testing and E2E testing in JS
Unit-testing and E2E testing in JSUnit-testing and E2E testing in JS
Unit-testing and E2E testing in JS
Michael Haberman
 
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
Goa App
 
Unit Testing JavaScript Applications
Unit Testing JavaScript ApplicationsUnit Testing JavaScript Applications
Unit Testing JavaScript Applications
Ynon Perek
 
4 mishchevskii - testing stage18-
4   mishchevskii - testing stage18-4   mishchevskii - testing stage18-
4 mishchevskii - testing stage18-
Ievgenii Katsan
 
Test automation expert days
Test automation   expert daysTest automation   expert days
Test automation expert days
Oren Rubin
 
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
Anup Singh
 
Testing nodejs apps
Testing nodejs appsTesting nodejs apps
Testing nodejs apps
felipefsilva
 
Type mock isolator
Type mock isolatorType mock isolator
Type mock isolator
MaslowB
 
Asynchronous development in JavaScript
Asynchronous development  in JavaScriptAsynchronous development  in JavaScript
Asynchronous development in JavaScript
Amitai Barnea
 
Boom! Promises/A+ Was Born
Boom! Promises/A+ Was BornBoom! Promises/A+ Was Born
Boom! Promises/A+ Was Born
Domenic Denicola
 
Avoiding callback hell with promises
Avoiding callback hell with promisesAvoiding callback hell with promises
Avoiding callback hell with promises
TorontoNodeJS
 
Testing in JavaScript - August 2018 - WebElement Bardejov
Testing in JavaScript - August 2018 - WebElement BardejovTesting in JavaScript - August 2018 - WebElement Bardejov
Testing in JavaScript - August 2018 - WebElement Bardejov
Marian Rusnak
 
Ad

Recently uploaded (20)

Porting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 WebinarPorting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 Webinar
ICS
 
Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3
Gaurav Sharma
 
Revolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management SoftwareRevolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management Software
Insurance Tech Services
 
Agile Software Engineering Methodologies
Agile Software Engineering MethodologiesAgile Software Engineering Methodologies
Agile Software Engineering Methodologies
Gaurav Sharma
 
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The SequelMarketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
BradBedford3
 
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps CyclesFrom Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
Marjukka Niinioja
 
Essentials of Resource Planning in a Downturn
Essentials of Resource Planning in a DownturnEssentials of Resource Planning in a Downturn
Essentials of Resource Planning in a Downturn
OnePlan Solutions
 
14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework
Angelo Theodorou
 
Maximizing Business Value with AWS Consulting Services.pdf
Maximizing Business Value with AWS Consulting Services.pdfMaximizing Business Value with AWS Consulting Services.pdf
Maximizing Business Value with AWS Consulting Services.pdf
Elena Mia
 
Code and No-Code Journeys: The Coverage Overlook
Code and No-Code Journeys: The Coverage OverlookCode and No-Code Journeys: The Coverage Overlook
Code and No-Code Journeys: The Coverage Overlook
Applitools
 
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdfTop 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Trackobit
 
Who will create the languages of the future?
Who will create the languages of the future?Who will create the languages of the future?
Who will create the languages of the future?
Jordi Cabot
 
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentricIntegration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Natan Silnitsky
 
Leveraging Foundation Models to Infer Intents
Leveraging Foundation Models to Infer IntentsLeveraging Foundation Models to Infer Intents
Leveraging Foundation Models to Infer Intents
Keheliya Gallaba
 
Best Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small BusinessesBest Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small Businesses
TheTelephony
 
Providing Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better DataProviding Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better Data
Safe Software
 
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
BradBedford3
 
Top 5 Task Management Software to Boost Productivity in 2025
Top 5 Task Management Software to Boost Productivity in 2025Top 5 Task Management Software to Boost Productivity in 2025
Top 5 Task Management Software to Boost Productivity in 2025
Orangescrum
 
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Wondershare PDFelement Pro 11.4.20.3548 Crack Free DownloadWondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Puppy jhon
 
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Alluxio, Inc.
 
Porting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 WebinarPorting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 Webinar
ICS
 
Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3
Gaurav Sharma
 
Revolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management SoftwareRevolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management Software
Insurance Tech Services
 
Agile Software Engineering Methodologies
Agile Software Engineering MethodologiesAgile Software Engineering Methodologies
Agile Software Engineering Methodologies
Gaurav Sharma
 
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The SequelMarketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
BradBedford3
 
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps CyclesFrom Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
Marjukka Niinioja
 
Essentials of Resource Planning in a Downturn
Essentials of Resource Planning in a DownturnEssentials of Resource Planning in a Downturn
Essentials of Resource Planning in a Downturn
OnePlan Solutions
 
14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework
Angelo Theodorou
 
Maximizing Business Value with AWS Consulting Services.pdf
Maximizing Business Value with AWS Consulting Services.pdfMaximizing Business Value with AWS Consulting Services.pdf
Maximizing Business Value with AWS Consulting Services.pdf
Elena Mia
 
Code and No-Code Journeys: The Coverage Overlook
Code and No-Code Journeys: The Coverage OverlookCode and No-Code Journeys: The Coverage Overlook
Code and No-Code Journeys: The Coverage Overlook
Applitools
 
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdfTop 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Trackobit
 
Who will create the languages of the future?
Who will create the languages of the future?Who will create the languages of the future?
Who will create the languages of the future?
Jordi Cabot
 
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentricIntegration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Natan Silnitsky
 
Leveraging Foundation Models to Infer Intents
Leveraging Foundation Models to Infer IntentsLeveraging Foundation Models to Infer Intents
Leveraging Foundation Models to Infer Intents
Keheliya Gallaba
 
Best Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small BusinessesBest Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small Businesses
TheTelephony
 
Providing Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better DataProviding Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better Data
Safe Software
 
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
BradBedford3
 
Top 5 Task Management Software to Boost Productivity in 2025
Top 5 Task Management Software to Boost Productivity in 2025Top 5 Task Management Software to Boost Productivity in 2025
Top 5 Task Management Software to Boost Productivity in 2025
Orangescrum
 
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Wondershare PDFelement Pro 11.4.20.3548 Crack Free DownloadWondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Puppy jhon
 
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Alluxio, Inc.
 
Ad

Async JavaScript Unit Testing

  • 1. Async JS Unit Testing Team: El Pimpi Mihail Gaberov
  • 2. Motivation ● To have all team/community members acknowledged in the field and be able to write unit test for our Javascript based projects. ● This could be continued as series of internal workshops in order to keep improving ourselves in all front-end skills that we need or might need.
  • 4. What is an async test? ● Unit tests for asynchronous code, code that returns promise of something that will happen in the future. it("Using a Promise with async/await that resolves successfully with wrong expectation!", async function() { var testPromise = new Promise(function(resolve, reject) { setTimeout(function() { resolve("Hello World!”); }, 200); }); var result = await testPromise; expect(result).to.equal("Hello!"); });
  • 5. How do we write JS unit tests? ● Callbacks - callbacks hell: “In a real codebase, each callback function might be quite long, which can result in huge and deeply indented functions. Dealing with this type of code, working with callbacks within callbacks within callbacks, is what is commonly referred to as "callback hell”." function callbackHell () { const api = new Api() let user, friends api.getUser().then(function (returnedUser) { user = returnedUser api.getFriends(user.id).then(function (returnedFriends) { friends = returnedFriends api.getPhoto(user.id).then(function (photo) { console.log('callbackHell', { user, friends, photo }) }) }) }) }
  • 6. ● Promises - they can be chained by returning another promise inside each callback, this way we can keep all of the callbacks on the same indentation level. We're also using arrow functions to abbreviate the callback function declarations. How do we write JS unit tests? “Promises are a new, built-in type of object that help you work with asynchronous code. A promise is a placeholder for a value that we don’t have yet but will at some later point. They’re especially good for working with multiple asynchronous steps.” function promiseChain () { const api = new Api() let user, friends api.getUser() .then((returnedUser) => { user = returnedUser return api.getFriends(user.id) }) .then((returnedFriends) => { friends = returnedFriends return api.getPhoto(user.id) }) .then((photo) => { console.log('promiseChain', { user, friends, photo }) }) }
  • 7. ● Generators - Generators are a special type of function. Whereas a standard function 
 produces at most a single value while running its code from start to finish, generators
 produce multiple values, on a per request basis, while suspending their execution 
 between these requests. How do we write JS unit tests? “A generator function is defined by putting an asterisk right after the function keyword. We can use the new yield keyword in generator functions.” function* WeaponGenerator(){ yield "Katana"; yield "Wakizashi"; yield "Kusarigama"; } for(let weapon of WeaponGenerator()) { assert(weapon !== undefined, weapon); } or const weaponsIterator = WeaponGenerator(); const result1 = weaponsIterator.next();
  • 8. ● Promises + Generators = Async await How do we write JS unit tests? “We put the code that uses asynchronous tasks in a generator, and we execute that generator function. When we reach a point in the generator execution that calls an asynchronous task, we create a promise that represents the value of that asynchronous task. Because we have no idea when that promise will be resolved (or even if it will be resolved), at this point of generator execution, we yield from the generator, so that we don’t cause blocking.” (async function (){ try { const ninjas = await getJSON("data/ninjas.json"); const missions = await getJSON(missions[0].missionsUrl); console.log(missions); } catch(e) { console.log("Error: ", e); } })() async(function*() { try { const ninjas = yield getJSON("data/ninjas.json"); const missions = yield getJSON(ninjas[0].missionsUrl); const missionDescription = yield getJSON(missions[0].detailsUrl); //All information received } catch(e) { //An error has occurred } });
  • 9. ● Sinonjs - test spies, stubs and mocks for JS How do we write JS unit tests? 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); }); });
  • 11. References: Simplifying Asynchronous Coding with Async Functions Error handling Promises in JavaScript Async/Await in JavaScript Testing Asynchronous Code with MochaJS and ES7 async/await Testing Asynchronous JavaScript Async/Await will make your code simpler Secrets of the JavaScript Ninja