SlideShare a Scribd company logo
Advanced JavaScript
Unit Testing
Lars Thorup
ZeaLake Software Consulting
April, 2015
Who is Lars Thorup?
● Software developer/architect
● JavaScript, C#
● Test Driven Development
● Continuous Integration
● Coach: Teaching TDD and
continuous integration
● Founder of ZeaLake
● @larsthorup
Best practices for JavaScript unit testing
● Asynchronous code: callbacks and promises
● Time and timers
● The DOM
● Ajax
● Cross-browser testing
● Leak detection
● Continuous testing
Asynchronous code: callbacks
● How to wait for the callback?
● Call done() when done! [Mocha, Jasmine]
https://github.com/larsthorup/mha2015-demo
it('should eventually return a+b', function () {
code.addSlow(4, 5, function (result) {
result.should.equal(9);
});
});
it('should eventually return a+b', function (done) {
code.addSlow(4, 5, function (result) {
result.should.equal(9);
done();
});
});
When this is called
the test has
already ended
Asynchronous code: promises
● Return a promise from the test [Mocha]
● Use promise matchers [chai-as-promised]
it('should eventually return a+b', function () {
return code.adding(4, 5).should.become(9);
});
https://github.com/larsthorup/mha2015-demo
Time and timers
● How to test delayed behavior fast?
● Fake the built-in timer! [Sinon, Jasmine]
beforeEach(function () {
this.sinon = sinon.sandbox.create();
this.sinon.useFakeTimers();
});
afterEach(function () {
this.sinon.restore();
});
it('should eventually return a+b', function () {
var adding = code.adding(4, 5);
this.sinon.clock.tick(500);
return adding.should.become(9);
});
https://github.com/larsthorup/mha2015-demo
The DOM
● Don't copy real markup
● Use the real thing if fast+easy (client side templating, RequireJS)
● Else inject minimal fake markup
● Use a fragment, or insert a fixture, don't use document
https://github.com/larsthorup/jsdevenv-mocha-require/blob/master/src/test/js/page/weather.test.js
it('listens', function () {
var context = $('<div><input type="text" id="city" /></div>');
weather.listen(context);
var city = context.find('#city');
city.val('San Francisco');
city.trigger('change');
expect(weather.fetch.calledWith('San Francisco')).to.equal(true);
});
CSS / responsive design
● Render into an iframe, then adjust size [quixote]
beforeEach(function () {
iframe = $('<iframe></iframe>').appendTo(fixture);
context = $(iframe.get(0).contentDocument);
$('<style></style>').text(menuCss).appendTo(context.find('head'));
var menu = $(multiline(function () {/*
<ul class="menu">
<li>Item 1</li>
<li>Item 2</li>
</ul>
*/})).appendTo(context.find('body'));
items = menu.find('li');
});
it('should turn horizontal when wide', function () {
iframe.attr('width', '401px');
expect(items.eq(0).offset().left).to.be.below(items.eq(1).offset().left);
expect(items.eq(0).offset().top).to.equal(items.eq(1).offset().top);
});
https://github.com/larsthorup/jsdevenv-mocha-require/blob/master/src/test/js/style/menu-responsive.test.js
Ajax
● Don't call any services
● Slow, fragile, setup heavy
● Mock or fake server responses [Sinon, mockjax]
https://github.com/larsthorup/jsdevenv-mocha-require/blob/master/src/test/js/page/weather.test.js
it('fetches', function (done) {
$.mockjax({
url: 'http://api.openweathermap.org/data/2.5/weather',
data: {q: 'Denver'},
responseText: {
weather: [{
description: 'sun'
}]
},
responseTime: 1
});
var fetching = weather.fetch('Denver');
fetching.then(function (data) {
expect(data.text).to.equal('sun');
done();
});
});
Ajax - generate mocks from real responses
● zealake.com/2015/01/05/unit-test-your-service-integration-layer/
https://github.com/larsthorup/mars/blob/master/test/util/api.proxy.js
https://github.com/larsthorup/mars/tree/master/demo/test/api-faker.js
Cross-browser testing
● Use Karma to run your tests in real browsers
● Also valuable for debugging
● Use browser services for continuous integration
● BrowserStack
● SauceLabs
https://github.com/larsthorup/jsdevenv-mocha-require/blob/master/Gruntfile.js
Leak detection
● To ensure that tests don't influence each other
● To make our code more reusable
● Use global beforeEach() and afterEach() [Mocha, Jasmine]
● Sample before, verify after
● window / global properties
● DOM elements
● localstorage keys
Wallaby.js
● Continuous Testing
● For JetBrains IDE's
● Visual Studio is in progress
● wallabyjs.com

More Related Content

What's hot (20)

Testing nightwatch, by David Torroija
Testing nightwatch, by David TorroijaTesting nightwatch, by David Torroija
Testing nightwatch, by David Torroija
David Torroija
 
Automated Frontend Testing
Automated Frontend TestingAutomated Frontend Testing
Automated Frontend Testing
Neil Crosby
 
Testing of React JS app
Testing of React JS appTesting of React JS app
Testing of React JS app
Aleks Zinevych
 
Service worker API
Service worker APIService worker API
Service worker API
Giorgio Natili
 
Fullstack End-to-end test automation with Node.js, one year later
Fullstack End-to-end test automation with Node.js, one year laterFullstack End-to-end test automation with Node.js, one year later
Fullstack End-to-end test automation with Node.js, one year later
Mek Srunyu Stittri
 
정오의 데이트 for iOS 코드 정리
정오의 데이트 for iOS 코드 정리정오의 데이트 for iOS 코드 정리
정오의 데이트 for iOS 코드 정리
태준 김
 
Testing in AngularJS
Testing in AngularJSTesting in AngularJS
Testing in AngularJS
Peter Drinnan
 
Night Watch with QA
Night Watch with QANight Watch with QA
Night Watch with QA
Carsten Sandtner
 
Node.js and Selenium Webdriver, a journey from the Java side
Node.js and Selenium Webdriver, a journey from the Java sideNode.js and Selenium Webdriver, a journey from the Java side
Node.js and Selenium Webdriver, a journey from the Java side
Mek Srunyu Stittri
 
RSpec
RSpecRSpec
RSpec
Marco Otte-Witte
 
Rails is not just Ruby
Rails is not just RubyRails is not just Ruby
Rails is not just Ruby
Marco Otte-Witte
 
Excellent
ExcellentExcellent
Excellent
Marco Otte-Witte
 
Symfony2 - Request to Response
Symfony2 - Request to ResponseSymfony2 - Request to Response
Symfony2 - Request to Response
Palko Lenard
 
JS Fest 2018. Сергей Пузанков. E2E-тестирование фронтенда c Hermione
JS Fest 2018. Сергей Пузанков. E2E-тестирование фронтенда c HermioneJS Fest 2018. Сергей Пузанков. E2E-тестирование фронтенда c Hermione
JS Fest 2018. Сергей Пузанков. E2E-тестирование фронтенда c Hermione
JSFestUA
 
Code ceptioninstallation
Code ceptioninstallationCode ceptioninstallation
Code ceptioninstallation
Andrii Lagovskiy
 
Service workers
Service workersService workers
Service workers
jungkees
 
Testing frontends with nightwatch & saucelabs
Testing frontends with nightwatch & saucelabsTesting frontends with nightwatch & saucelabs
Testing frontends with nightwatch & saucelabs
Tudor Barbu
 
SFScon17 - Paolo D'Incau: "Build, test and release your software using Free S...
SFScon17 - Paolo D'Incau: "Build, test and release your software using Free S...SFScon17 - Paolo D'Incau: "Build, test and release your software using Free S...
SFScon17 - Paolo D'Incau: "Build, test and release your software using Free S...
South Tyrol Free Software Conference
 
遠端團隊專案建立與管理 remote team management 2016
遠端團隊專案建立與管理 remote team management 2016遠端團隊專案建立與管理 remote team management 2016
遠端團隊專案建立與管理 remote team management 2016
Caesar Chi
 
MLBlock
MLBlockMLBlock
MLBlock
Nat Weerawan
 
Testing nightwatch, by David Torroija
Testing nightwatch, by David TorroijaTesting nightwatch, by David Torroija
Testing nightwatch, by David Torroija
David Torroija
 
Automated Frontend Testing
Automated Frontend TestingAutomated Frontend Testing
Automated Frontend Testing
Neil Crosby
 
Testing of React JS app
Testing of React JS appTesting of React JS app
Testing of React JS app
Aleks Zinevych
 
Fullstack End-to-end test automation with Node.js, one year later
Fullstack End-to-end test automation with Node.js, one year laterFullstack End-to-end test automation with Node.js, one year later
Fullstack End-to-end test automation with Node.js, one year later
Mek Srunyu Stittri
 
정오의 데이트 for iOS 코드 정리
정오의 데이트 for iOS 코드 정리정오의 데이트 for iOS 코드 정리
정오의 데이트 for iOS 코드 정리
태준 김
 
Testing in AngularJS
Testing in AngularJSTesting in AngularJS
Testing in AngularJS
Peter Drinnan
 
Node.js and Selenium Webdriver, a journey from the Java side
Node.js and Selenium Webdriver, a journey from the Java sideNode.js and Selenium Webdriver, a journey from the Java side
Node.js and Selenium Webdriver, a journey from the Java side
Mek Srunyu Stittri
 
Symfony2 - Request to Response
Symfony2 - Request to ResponseSymfony2 - Request to Response
Symfony2 - Request to Response
Palko Lenard
 
JS Fest 2018. Сергей Пузанков. E2E-тестирование фронтенда c Hermione
JS Fest 2018. Сергей Пузанков. E2E-тестирование фронтенда c HermioneJS Fest 2018. Сергей Пузанков. E2E-тестирование фронтенда c Hermione
JS Fest 2018. Сергей Пузанков. E2E-тестирование фронтенда c Hermione
JSFestUA
 
Service workers
Service workersService workers
Service workers
jungkees
 
Testing frontends with nightwatch & saucelabs
Testing frontends with nightwatch & saucelabsTesting frontends with nightwatch & saucelabs
Testing frontends with nightwatch & saucelabs
Tudor Barbu
 
SFScon17 - Paolo D'Incau: "Build, test and release your software using Free S...
SFScon17 - Paolo D'Incau: "Build, test and release your software using Free S...SFScon17 - Paolo D'Incau: "Build, test and release your software using Free S...
SFScon17 - Paolo D'Incau: "Build, test and release your software using Free S...
South Tyrol Free Software Conference
 
遠端團隊專案建立與管理 remote team management 2016
遠端團隊專案建立與管理 remote team management 2016遠端團隊專案建立與管理 remote team management 2016
遠端團隊專案建立與管理 remote team management 2016
Caesar Chi
 

Similar to Advanced Javascript Unit Testing (20)

Testing JavaScript with Jasmine in Rails Applications
Testing JavaScript with Jasmine in Rails Applications Testing JavaScript with Jasmine in Rails Applications
Testing JavaScript with Jasmine in Rails Applications
Hector Correa
 
Good karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with KarmaGood karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with Karma
ExoLeaders.com
 
Primefaces Nextgen Lju
Primefaces Nextgen LjuPrimefaces Nextgen Lju
Primefaces Nextgen Lju
Skills Matter
 
Primefaces Nextgen Lju
Primefaces Nextgen LjuPrimefaces Nextgen Lju
Primefaces Nextgen Lju
Skills Matter
 
Guia de Sobrevivência JS no mundo Open Source
Guia de Sobrevivência JS no mundo Open SourceGuia de Sobrevivência JS no mundo Open Source
Guia de Sobrevivência JS no mundo Open Source
Leonardo Balter
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
Ran Mizrahi
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
David Padbury
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenery
toddbr
 
Express Presentation
Express PresentationExpress Presentation
Express Presentation
aaronheckmann
 
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
 
Node.js vs Play Framework (with Japanese subtitles)
Node.js vs Play Framework (with Japanese subtitles)Node.js vs Play Framework (with Japanese subtitles)
Node.js vs Play Framework (with Japanese subtitles)
Yevgeniy Brikman
 
Cross Domain Web
Mashups with JQuery and Google App Engine
Cross Domain Web
Mashups with JQuery and Google App EngineCross Domain Web
Mashups with JQuery and Google App Engine
Cross Domain Web
Mashups with JQuery and Google App Engine
Andy McKay
 
JS Class 2016
JS Class 2016JS Class 2016
JS Class 2016
Yves-Emmanuel Jutard
 
JS class slides (2016)
JS class slides (2016)JS class slides (2016)
JS class slides (2016)
Yves-Emmanuel Jutard
 
Enhance Web Performance
Enhance Web PerformanceEnhance Web Performance
Enhance Web Performance
Adam Lu
 
Designing and developing mobile web applications with Mockup, Sencha Touch an...
Designing and developing mobile web applications with Mockup, Sencha Touch an...Designing and developing mobile web applications with Mockup, Sencha Touch an...
Designing and developing mobile web applications with Mockup, Sencha Touch an...
Matteo Collina
 
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
BradNeuberg
 
Accelerated Adoption: HTML5 and CSS3 for ASP.NET Developers
Accelerated Adoption: HTML5 and CSS3 for ASP.NET DevelopersAccelerated Adoption: HTML5 and CSS3 for ASP.NET Developers
Accelerated Adoption: HTML5 and CSS3 for ASP.NET Developers
Todd Anglin
 
Non Conventional Android Programming En
Non Conventional Android Programming EnNon Conventional Android Programming En
Non Conventional Android Programming En
guest9bcef2f
 
Non Conventional Android Programming (English)
Non Conventional Android Programming (English)Non Conventional Android Programming (English)
Non Conventional Android Programming (English)
Davide Cerbo
 
Testing JavaScript with Jasmine in Rails Applications
Testing JavaScript with Jasmine in Rails Applications Testing JavaScript with Jasmine in Rails Applications
Testing JavaScript with Jasmine in Rails Applications
Hector Correa
 
Good karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with KarmaGood karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with Karma
ExoLeaders.com
 
Primefaces Nextgen Lju
Primefaces Nextgen LjuPrimefaces Nextgen Lju
Primefaces Nextgen Lju
Skills Matter
 
Primefaces Nextgen Lju
Primefaces Nextgen LjuPrimefaces Nextgen Lju
Primefaces Nextgen Lju
Skills Matter
 
Guia de Sobrevivência JS no mundo Open Source
Guia de Sobrevivência JS no mundo Open SourceGuia de Sobrevivência JS no mundo Open Source
Guia de Sobrevivência JS no mundo Open Source
Leonardo Balter
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
Ran Mizrahi
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
David Padbury
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenery
toddbr
 
Express Presentation
Express PresentationExpress Presentation
Express Presentation
aaronheckmann
 
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
 
Node.js vs Play Framework (with Japanese subtitles)
Node.js vs Play Framework (with Japanese subtitles)Node.js vs Play Framework (with Japanese subtitles)
Node.js vs Play Framework (with Japanese subtitles)
Yevgeniy Brikman
 
Cross Domain Web
Mashups with JQuery and Google App Engine
Cross Domain Web
Mashups with JQuery and Google App EngineCross Domain Web
Mashups with JQuery and Google App Engine
Cross Domain Web
Mashups with JQuery and Google App Engine
Andy McKay
 
Enhance Web Performance
Enhance Web PerformanceEnhance Web Performance
Enhance Web Performance
Adam Lu
 
Designing and developing mobile web applications with Mockup, Sencha Touch an...
Designing and developing mobile web applications with Mockup, Sencha Touch an...Designing and developing mobile web applications with Mockup, Sencha Touch an...
Designing and developing mobile web applications with Mockup, Sencha Touch an...
Matteo Collina
 
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
BradNeuberg
 
Accelerated Adoption: HTML5 and CSS3 for ASP.NET Developers
Accelerated Adoption: HTML5 and CSS3 for ASP.NET DevelopersAccelerated Adoption: HTML5 and CSS3 for ASP.NET Developers
Accelerated Adoption: HTML5 and CSS3 for ASP.NET Developers
Todd Anglin
 
Non Conventional Android Programming En
Non Conventional Android Programming EnNon Conventional Android Programming En
Non Conventional Android Programming En
guest9bcef2f
 
Non Conventional Android Programming (English)
Non Conventional Android Programming (English)Non Conventional Android Programming (English)
Non Conventional Android Programming (English)
Davide Cerbo
 
Ad

More from Lars Thorup (19)

100 tests per second - 40 releases per week
100 tests per second - 40 releases per week100 tests per second - 40 releases per week
100 tests per second - 40 releases per week
Lars Thorup
 
SQL or NoSQL - how to choose
SQL or NoSQL - how to chooseSQL or NoSQL - how to choose
SQL or NoSQL - how to choose
Lars Thorup
 
Super fast end-to-end-tests
Super fast end-to-end-testsSuper fast end-to-end-tests
Super fast end-to-end-tests
Lars Thorup
 
Extreme Programming - to the next-level
Extreme Programming - to the next-levelExtreme Programming - to the next-level
Extreme Programming - to the next-level
Lars Thorup
 
Unit testing legacy code
Unit testing legacy codeUnit testing legacy code
Unit testing legacy code
Lars Thorup
 
Advanced QUnit - Front-End JavaScript Unit Testing
Advanced QUnit - Front-End JavaScript Unit TestingAdvanced QUnit - Front-End JavaScript Unit Testing
Advanced QUnit - Front-End JavaScript Unit Testing
Lars Thorup
 
Put "fast" back in "fast feedback"
Put "fast" back in "fast feedback"Put "fast" back in "fast feedback"
Put "fast" back in "fast feedback"
Lars Thorup
 
Database Schema Evolution
Database Schema EvolutionDatabase Schema Evolution
Database Schema Evolution
Lars Thorup
 
Advanced Jasmine - Front-End JavaScript Unit Testing
Advanced Jasmine - Front-End JavaScript Unit TestingAdvanced Jasmine - Front-End JavaScript Unit Testing
Advanced Jasmine - Front-End JavaScript Unit Testing
Lars Thorup
 
Javascript unit testing with QUnit and Sinon
Javascript unit testing with QUnit and SinonJavascript unit testing with QUnit and Sinon
Javascript unit testing with QUnit and Sinon
Lars Thorup
 
Continuous Integration for front-end JavaScript
Continuous Integration for front-end JavaScriptContinuous Integration for front-end JavaScript
Continuous Integration for front-end JavaScript
Lars Thorup
 
Automated Performance Testing
Automated Performance TestingAutomated Performance Testing
Automated Performance Testing
Lars Thorup
 
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
 
Agile Contracts
Agile ContractsAgile Contracts
Agile Contracts
Lars Thorup
 
High Performance Software Engineering Teams
High Performance Software Engineering TeamsHigh Performance Software Engineering Teams
High Performance Software Engineering Teams
Lars Thorup
 
Elephant Carpaccio
Elephant CarpaccioElephant Carpaccio
Elephant Carpaccio
Lars Thorup
 
Automated Testing for Embedded Software in C or C++
Automated Testing for Embedded Software in C or C++Automated Testing for Embedded Software in C or C++
Automated Testing for Embedded Software in C or C++
Lars Thorup
 
Unit Testing in JavaScript with MVC and QUnit
Unit Testing in JavaScript with MVC and QUnitUnit Testing in JavaScript with MVC and QUnit
Unit Testing in JavaScript with MVC and QUnit
Lars Thorup
 
Introduction to Automated Testing
Introduction to Automated TestingIntroduction to Automated Testing
Introduction to Automated Testing
Lars Thorup
 
100 tests per second - 40 releases per week
100 tests per second - 40 releases per week100 tests per second - 40 releases per week
100 tests per second - 40 releases per week
Lars Thorup
 
SQL or NoSQL - how to choose
SQL or NoSQL - how to chooseSQL or NoSQL - how to choose
SQL or NoSQL - how to choose
Lars Thorup
 
Super fast end-to-end-tests
Super fast end-to-end-testsSuper fast end-to-end-tests
Super fast end-to-end-tests
Lars Thorup
 
Extreme Programming - to the next-level
Extreme Programming - to the next-levelExtreme Programming - to the next-level
Extreme Programming - to the next-level
Lars Thorup
 
Unit testing legacy code
Unit testing legacy codeUnit testing legacy code
Unit testing legacy code
Lars Thorup
 
Advanced QUnit - Front-End JavaScript Unit Testing
Advanced QUnit - Front-End JavaScript Unit TestingAdvanced QUnit - Front-End JavaScript Unit Testing
Advanced QUnit - Front-End JavaScript Unit Testing
Lars Thorup
 
Put "fast" back in "fast feedback"
Put "fast" back in "fast feedback"Put "fast" back in "fast feedback"
Put "fast" back in "fast feedback"
Lars Thorup
 
Database Schema Evolution
Database Schema EvolutionDatabase Schema Evolution
Database Schema Evolution
Lars Thorup
 
Advanced Jasmine - Front-End JavaScript Unit Testing
Advanced Jasmine - Front-End JavaScript Unit TestingAdvanced Jasmine - Front-End JavaScript Unit Testing
Advanced Jasmine - Front-End JavaScript Unit Testing
Lars Thorup
 
Javascript unit testing with QUnit and Sinon
Javascript unit testing with QUnit and SinonJavascript unit testing with QUnit and Sinon
Javascript unit testing with QUnit and Sinon
Lars Thorup
 
Continuous Integration for front-end JavaScript
Continuous Integration for front-end JavaScriptContinuous Integration for front-end JavaScript
Continuous Integration for front-end JavaScript
Lars Thorup
 
Automated Performance Testing
Automated Performance TestingAutomated Performance Testing
Automated Performance Testing
Lars Thorup
 
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
 
High Performance Software Engineering Teams
High Performance Software Engineering TeamsHigh Performance Software Engineering Teams
High Performance Software Engineering Teams
Lars Thorup
 
Elephant Carpaccio
Elephant CarpaccioElephant Carpaccio
Elephant Carpaccio
Lars Thorup
 
Automated Testing for Embedded Software in C or C++
Automated Testing for Embedded Software in C or C++Automated Testing for Embedded Software in C or C++
Automated Testing for Embedded Software in C or C++
Lars Thorup
 
Unit Testing in JavaScript with MVC and QUnit
Unit Testing in JavaScript with MVC and QUnitUnit Testing in JavaScript with MVC and QUnit
Unit Testing in JavaScript with MVC and QUnit
Lars Thorup
 
Introduction to Automated Testing
Introduction to Automated TestingIntroduction to Automated Testing
Introduction to Automated Testing
Lars Thorup
 
Ad

Recently uploaded (20)

Providing an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME FlowProviding an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME Flow
Safe Software
 
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data ResilienceFloods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Safe Software
 
Artificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdfArtificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdf
OnBoard
 
Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.
hok12341073
 
The State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry ReportThe State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry Report
Liveplex
 
Ben Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding WorldBen Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding World
AWS Chicago
 
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
NTT DATA Technology & Innovation
 
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
Edge AI and Vision Alliance
 
Crypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdfCrypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdf
Stephen Perrenod
 
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
Introduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUEIntroduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUE
Google Developer Group On Campus European Universities in Egypt
 
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und AnwendungsfälleDomino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
panagenda
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too LateKubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven InfrastructureNo-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FMEEnabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdfvertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
Providing an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME FlowProviding an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME Flow
Safe Software
 
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data ResilienceFloods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Safe Software
 
Artificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdfArtificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdf
OnBoard
 
Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.
hok12341073
 
The State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry ReportThe State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry Report
Liveplex
 
Ben Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding WorldBen Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding World
AWS Chicago
 
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
NTT DATA Technology & Innovation
 
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
Edge AI and Vision Alliance
 
Crypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdfCrypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdf
Stephen Perrenod
 
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und AnwendungsfälleDomino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
panagenda
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too LateKubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven InfrastructureNo-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FMEEnabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdfvertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 

Advanced Javascript Unit Testing

  • 1. Advanced JavaScript Unit Testing Lars Thorup ZeaLake Software Consulting April, 2015
  • 2. Who is Lars Thorup? ● Software developer/architect ● JavaScript, C# ● Test Driven Development ● Continuous Integration ● Coach: Teaching TDD and continuous integration ● Founder of ZeaLake ● @larsthorup
  • 3. Best practices for JavaScript unit testing ● Asynchronous code: callbacks and promises ● Time and timers ● The DOM ● Ajax ● Cross-browser testing ● Leak detection ● Continuous testing
  • 4. Asynchronous code: callbacks ● How to wait for the callback? ● Call done() when done! [Mocha, Jasmine] https://github.com/larsthorup/mha2015-demo it('should eventually return a+b', function () { code.addSlow(4, 5, function (result) { result.should.equal(9); }); }); it('should eventually return a+b', function (done) { code.addSlow(4, 5, function (result) { result.should.equal(9); done(); }); }); When this is called the test has already ended
  • 5. Asynchronous code: promises ● Return a promise from the test [Mocha] ● Use promise matchers [chai-as-promised] it('should eventually return a+b', function () { return code.adding(4, 5).should.become(9); }); https://github.com/larsthorup/mha2015-demo
  • 6. Time and timers ● How to test delayed behavior fast? ● Fake the built-in timer! [Sinon, Jasmine] beforeEach(function () { this.sinon = sinon.sandbox.create(); this.sinon.useFakeTimers(); }); afterEach(function () { this.sinon.restore(); }); it('should eventually return a+b', function () { var adding = code.adding(4, 5); this.sinon.clock.tick(500); return adding.should.become(9); }); https://github.com/larsthorup/mha2015-demo
  • 7. The DOM ● Don't copy real markup ● Use the real thing if fast+easy (client side templating, RequireJS) ● Else inject minimal fake markup ● Use a fragment, or insert a fixture, don't use document https://github.com/larsthorup/jsdevenv-mocha-require/blob/master/src/test/js/page/weather.test.js it('listens', function () { var context = $('<div><input type="text" id="city" /></div>'); weather.listen(context); var city = context.find('#city'); city.val('San Francisco'); city.trigger('change'); expect(weather.fetch.calledWith('San Francisco')).to.equal(true); });
  • 8. CSS / responsive design ● Render into an iframe, then adjust size [quixote] beforeEach(function () { iframe = $('<iframe></iframe>').appendTo(fixture); context = $(iframe.get(0).contentDocument); $('<style></style>').text(menuCss).appendTo(context.find('head')); var menu = $(multiline(function () {/* <ul class="menu"> <li>Item 1</li> <li>Item 2</li> </ul> */})).appendTo(context.find('body')); items = menu.find('li'); }); it('should turn horizontal when wide', function () { iframe.attr('width', '401px'); expect(items.eq(0).offset().left).to.be.below(items.eq(1).offset().left); expect(items.eq(0).offset().top).to.equal(items.eq(1).offset().top); }); https://github.com/larsthorup/jsdevenv-mocha-require/blob/master/src/test/js/style/menu-responsive.test.js
  • 9. Ajax ● Don't call any services ● Slow, fragile, setup heavy ● Mock or fake server responses [Sinon, mockjax] https://github.com/larsthorup/jsdevenv-mocha-require/blob/master/src/test/js/page/weather.test.js it('fetches', function (done) { $.mockjax({ url: 'http://api.openweathermap.org/data/2.5/weather', data: {q: 'Denver'}, responseText: { weather: [{ description: 'sun' }] }, responseTime: 1 }); var fetching = weather.fetch('Denver'); fetching.then(function (data) { expect(data.text).to.equal('sun'); done(); }); });
  • 10. Ajax - generate mocks from real responses ● zealake.com/2015/01/05/unit-test-your-service-integration-layer/ https://github.com/larsthorup/mars/blob/master/test/util/api.proxy.js https://github.com/larsthorup/mars/tree/master/demo/test/api-faker.js
  • 11. Cross-browser testing ● Use Karma to run your tests in real browsers ● Also valuable for debugging ● Use browser services for continuous integration ● BrowserStack ● SauceLabs https://github.com/larsthorup/jsdevenv-mocha-require/blob/master/Gruntfile.js
  • 12. Leak detection ● To ensure that tests don't influence each other ● To make our code more reusable ● Use global beforeEach() and afterEach() [Mocha, Jasmine] ● Sample before, verify after ● window / global properties ● DOM elements ● localstorage keys
  • 13. Wallaby.js ● Continuous Testing ● For JetBrains IDE's ● Visual Studio is in progress ● wallabyjs.com