SlideShare a Scribd company logo
Unit Testing With Javascript*
(There maybe some coffeescript too)
Types of test
● Unit
● Integration
● Acceptance
● Manual
Types of test
● Unit
● Integration
● Acceptance
● Manual
Volume
Types of test
● Unit – developer
● Integration – developer
● Acceptance – developer / Tester
● Manual – developer / Tester
Why Write Unit Tests?
● Show what's broken after development.
● Quickest way to prove most code.
● Code that is hard to test, probably should be
rewritten.
● Gain confidence when developing with limited
domain knowledge.
● Can document how code is meant to behave.
http://www.onjava.com/pub/a/onjava/2003/04/02/javaxpckbk.html
Frameworks
● Qunit
● Jasmine
● Mocha
● Bespoke
Framework
Mocha
Best practices
● Generally one class per file.
● Follow the same directory structure as the
application.
● If a class has lots of tests? Use many files!
● Only test method's input and output.
● Move big tests to specific integration tests.
● Should be easy to read.
● No existing tests? Write some :-)
Describe and It
define (require, exports, module) ->
Device = require 'lib/device'
describe "Device", ->
device = null
describe "constructor()", ->
before ->
device = new Device
it "defaults to online", ->
device.online().should.equa true
It's not optimal
describe "Device", ->
describe "platform()", ->
it "returns the correct platform", ->
device = new Device 'ios'
platform = device.platform()
platform.should.be.an.instanceOf object
platform.version.should.equal 5
Platform.os.should.match /apple/
It's also not optimal
describe "Device", ->
describe "constructor()", ->
it "defaults to online when on ios", ->
device = new Device 'ios'
device.online().should.equal true
it "defaults to online when on android", ->
device = new Device 'android'
device.online().should.equal true
Ellie the anti tech cat!
Contexts
describe "constructor()", ->
context “on android”, ->
before ->
device = new Device 'android'
it "defaults to online", ->
device.online().should.equal true
context “on iOS”, →
before ->
device = new Device 'iOS'
it "defaults to offline", ->
device.online().should.equal false
Before, BeforeEach, After, AfterEach
● Jasmine does not have “before” and “after”.
● Run order
– Before
– BeforeEach
– It
– AfterEach
– After
● Can be nested inside “describe” and “context”.
Assertions
● Node.js assert()
assert.equal(var, 'foo')
● Jasmine expect()
expect(var).toBe('foo')
● Chai should
var.should.equal('foo')
Chai FTW
● var.should.be.a('string')
● var.should.not.be.an('object')
● var.should.have.property('erm').with.length(3)
● var.should.be.at.most(5)
● var.to.be.within(5, 10)
Exceptions
(->
throw new Error 'bad thing'
).should.throw /bad/
(->
throw new Error 'really bad thing'
).should.not.throw 'bad thing'
(function(){
throw new Error('bad thing');
}).should.throw(/bad/);
Spies and Stubs
spy = null
before ->
spy = sinon.spy User::, '_sendPasswordEmail'
user = new User 'bob jones'
user.forgottenPassword()
after ->
spy.restore()
it 'sends an email'
spy.should.of.been.calledOnce
Factories
● Instances of application classes used in tests
can require complex setup.
● DRY, define several types of instance for
different use cases, eg:
– Logged in user
– Logged out user
From this...
user = null
before ->
user = new User
name: 'bob jones'
email: 'bobjones@aol.com'
loggedIn: true
Bookings: [
ref: 'abc123'
,
ref: 'abc124'
]
...to this
UserFixtures = require 'fixtures/user'
user = null
before ->
user = UserFixtures.loggedInWithBookings()
Fake Server
● When code needs an external request.
server = null
results = null
before ->
server = sinon.fakeServer.create()
server.respondWith //availability/, (xhr) →
xhr.respond 200,
error: 'no matches'
results = new AvailabilitySearch
server.respond()
after ->
server.restore()
Fixtures
● Examples of data.
● Can be server responses, database rows or
collection info.
● Normally in JSON format for easy handling.
lotsOfBookings = require 'json!spec/fixtures/lots_of_bookings.json'
Collection = null
before ->
collection = new Bookings lotsOfBookings
Questions?

More Related Content

What's hot (20)

KEY
Like a Genie from a Lamp: Headless JavaScript Unit Testing with Jasmine and P...
Rob Friesel
 
PDF
Painless JavaScript Testing with Jest
Michał Pierzchała
 
PPT
Js unit testing
Mihail Irintchev
 
KEY
Requirejs
sioked
 
PDF
Detecting headless browsers
Sergey Shekyan
 
PDF
Survive JavaScript - Strategies and Tricks
Juho Vepsäläinen
 
PDF
One step in the future: CSS variables
Giacomo Zinetti
 
PDF
Intro to node.js - Ran Mizrahi (28/8/14)
Ran Mizrahi
 
PPTX
Workshop Intro: FrontEnd General Overview
Visual Engineering
 
PPTX
Jasmine with JS-Test-Driver
Devesh Chanchlani
 
PPTX
Unit testing JavaScript: Jasmine & karma intro
Maurice De Beijer [MVP]
 
PDF
Requirejs
Jason Lotito
 
PDF
Workshop 4: NodeJS. Express Framework & MongoDB.
Visual Engineering
 
PDF
JavaScript Test-Driven Development with Jasmine 2.0 and Karma
Christopher Bartling
 
PDF
Server-Side JavaScript with Nashorn
Daniel Woods
 
PDF
Developing large scale JavaScript applications
Milan Korsos
 
PPSX
RequireJS
Tim Doherty
 
PPTX
Testing frontends with nightwatch & saucelabs
Tudor Barbu
 
PDF
CasperJS and PhantomJS for Automated Testing
X-Team
 
Like a Genie from a Lamp: Headless JavaScript Unit Testing with Jasmine and P...
Rob Friesel
 
Painless JavaScript Testing with Jest
Michał Pierzchała
 
Js unit testing
Mihail Irintchev
 
Requirejs
sioked
 
Detecting headless browsers
Sergey Shekyan
 
Survive JavaScript - Strategies and Tricks
Juho Vepsäläinen
 
One step in the future: CSS variables
Giacomo Zinetti
 
Intro to node.js - Ran Mizrahi (28/8/14)
Ran Mizrahi
 
Workshop Intro: FrontEnd General Overview
Visual Engineering
 
Jasmine with JS-Test-Driver
Devesh Chanchlani
 
Unit testing JavaScript: Jasmine & karma intro
Maurice De Beijer [MVP]
 
Requirejs
Jason Lotito
 
Workshop 4: NodeJS. Express Framework & MongoDB.
Visual Engineering
 
JavaScript Test-Driven Development with Jasmine 2.0 and Karma
Christopher Bartling
 
Server-Side JavaScript with Nashorn
Daniel Woods
 
Developing large scale JavaScript applications
Milan Korsos
 
RequireJS
Tim Doherty
 
Testing frontends with nightwatch & saucelabs
Tudor Barbu
 
CasperJS and PhantomJS for Automated Testing
X-Team
 

Viewers also liked (6)

PDF
Javascript Unit Testing Tools
PixelCrayons
 
PPT
JavaScript Unit Testing
Christian Johansen
 
PPT
Testing of javacript
Lei Kang
 
PPTX
Testing Javascript Apps with Mocha and Chai
Andrew Winder
 
PDF
Unit testing JavaScript using Mocha and Node
Josh Mock
 
PPT
JavaScript Testing: Mocha + Chai
James Cryer
 
Javascript Unit Testing Tools
PixelCrayons
 
JavaScript Unit Testing
Christian Johansen
 
Testing of javacript
Lei Kang
 
Testing Javascript Apps with Mocha and Chai
Andrew Winder
 
Unit testing JavaScript using Mocha and Node
Josh Mock
 
JavaScript Testing: Mocha + Chai
James Cryer
 
Ad

Similar to Unit Testing With Javascript (20)

PDF
3 WAYS TO TEST YOUR COLDFUSION API
Gavin Pickin
 
PDF
3 WAYS TO TEST YOUR COLDFUSION API -
Ortus Solutions, Corp
 
PPTX
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
Ortus Solutions, Corp
 
PPTX
How do I write Testable Javascript so I can Test my CF API on Server and Client
Gavin Pickin
 
PDF
Developers Testing - Girl Code at bloomon
Ineke Scheffers
 
PDF
Quick tour to front end unit testing using jasmine
Gil Fink
 
PDF
An Introduction to the World of Testing for Front-End Developers
FITC
 
PDF
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End ...
Haris Mahmood
 
PPTX
jasmine
Asanka Indrajith
 
PDF
JavaScript TDD with Jasmine and Karma
Christopher Bartling
 
PDF
How to write Testable Javascript
ColdFusionConference
 
PDF
How do I write Testable Javascript - Presented at dev.Objective() June 16, 2016
Gavin Pickin
 
PDF
Jasmine - why JS tests don't smell fishy
Igor Napierala
 
PDF
JS Lab`16. Сергей Селецкий: "Ретроспектива тестирования JavaScript"
GeeksLab Odessa
 
PDF
Intro To JavaScript Unit Testing - Ran Mizrahi
Ran Mizrahi
 
PPTX
Javascript Testing with Jasmine 101
Roy Yu
 
PPT
Test innode
Davide Fiorello
 
PDF
mocha sinon chai Dc jquery 4-24
Carson Banov
 
PPTX
Full Stack Unit Testing
GlobalLogic Ukraine
 
PDF
How do I Write Testable Javascript so I can Test my CF API on Server and Client
ColdFusionConference
 
3 WAYS TO TEST YOUR COLDFUSION API
Gavin Pickin
 
3 WAYS TO TEST YOUR COLDFUSION API -
Ortus Solutions, Corp
 
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
Ortus Solutions, Corp
 
How do I write Testable Javascript so I can Test my CF API on Server and Client
Gavin Pickin
 
Developers Testing - Girl Code at bloomon
Ineke Scheffers
 
Quick tour to front end unit testing using jasmine
Gil Fink
 
An Introduction to the World of Testing for Front-End Developers
FITC
 
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End ...
Haris Mahmood
 
JavaScript TDD with Jasmine and Karma
Christopher Bartling
 
How to write Testable Javascript
ColdFusionConference
 
How do I write Testable Javascript - Presented at dev.Objective() June 16, 2016
Gavin Pickin
 
Jasmine - why JS tests don't smell fishy
Igor Napierala
 
JS Lab`16. Сергей Селецкий: "Ретроспектива тестирования JavaScript"
GeeksLab Odessa
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Ran Mizrahi
 
Javascript Testing with Jasmine 101
Roy Yu
 
Test innode
Davide Fiorello
 
mocha sinon chai Dc jquery 4-24
Carson Banov
 
Full Stack Unit Testing
GlobalLogic Ukraine
 
How do I Write Testable Javascript so I can Test my CF API on Server and Client
ColdFusionConference
 
Ad

Recently uploaded (20)

PPTX
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
PPTX
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PDF
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
PDF
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PDF
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
PPTX
Digital Circuits, important subject in CS
contactparinay1
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PDF
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
Digital Circuits, important subject in CS
contactparinay1
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 

Unit Testing With Javascript

  • 1. Unit Testing With Javascript*
  • 2. (There maybe some coffeescript too)
  • 3. Types of test ● Unit ● Integration ● Acceptance ● Manual
  • 4. Types of test ● Unit ● Integration ● Acceptance ● Manual Volume
  • 5. Types of test ● Unit – developer ● Integration – developer ● Acceptance – developer / Tester ● Manual – developer / Tester
  • 6. Why Write Unit Tests? ● Show what's broken after development. ● Quickest way to prove most code. ● Code that is hard to test, probably should be rewritten. ● Gain confidence when developing with limited domain knowledge. ● Can document how code is meant to behave. http://www.onjava.com/pub/a/onjava/2003/04/02/javaxpckbk.html
  • 9. Best practices ● Generally one class per file. ● Follow the same directory structure as the application. ● If a class has lots of tests? Use many files! ● Only test method's input and output. ● Move big tests to specific integration tests. ● Should be easy to read. ● No existing tests? Write some :-)
  • 10. Describe and It define (require, exports, module) -> Device = require 'lib/device' describe "Device", -> device = null describe "constructor()", -> before -> device = new Device it "defaults to online", -> device.online().should.equa true
  • 11. It's not optimal describe "Device", -> describe "platform()", -> it "returns the correct platform", -> device = new Device 'ios' platform = device.platform() platform.should.be.an.instanceOf object platform.version.should.equal 5 Platform.os.should.match /apple/
  • 12. It's also not optimal describe "Device", -> describe "constructor()", -> it "defaults to online when on ios", -> device = new Device 'ios' device.online().should.equal true it "defaults to online when on android", -> device = new Device 'android' device.online().should.equal true
  • 13. Ellie the anti tech cat!
  • 14. Contexts describe "constructor()", -> context “on android”, -> before -> device = new Device 'android' it "defaults to online", -> device.online().should.equal true context “on iOS”, → before -> device = new Device 'iOS' it "defaults to offline", -> device.online().should.equal false
  • 15. Before, BeforeEach, After, AfterEach ● Jasmine does not have “before” and “after”. ● Run order – Before – BeforeEach – It – AfterEach – After ● Can be nested inside “describe” and “context”.
  • 16. Assertions ● Node.js assert() assert.equal(var, 'foo') ● Jasmine expect() expect(var).toBe('foo') ● Chai should var.should.equal('foo')
  • 17. Chai FTW ● var.should.be.a('string') ● var.should.not.be.an('object') ● var.should.have.property('erm').with.length(3) ● var.should.be.at.most(5) ● var.to.be.within(5, 10)
  • 18. Exceptions (-> throw new Error 'bad thing' ).should.throw /bad/ (-> throw new Error 'really bad thing' ).should.not.throw 'bad thing' (function(){ throw new Error('bad thing'); }).should.throw(/bad/);
  • 19. Spies and Stubs spy = null before -> spy = sinon.spy User::, '_sendPasswordEmail' user = new User 'bob jones' user.forgottenPassword() after -> spy.restore() it 'sends an email' spy.should.of.been.calledOnce
  • 20. Factories ● Instances of application classes used in tests can require complex setup. ● DRY, define several types of instance for different use cases, eg: – Logged in user – Logged out user
  • 21. From this... user = null before -> user = new User name: 'bob jones' email: '[email protected]' loggedIn: true Bookings: [ ref: 'abc123' , ref: 'abc124' ]
  • 22. ...to this UserFixtures = require 'fixtures/user' user = null before -> user = UserFixtures.loggedInWithBookings()
  • 23. Fake Server ● When code needs an external request. server = null results = null before -> server = sinon.fakeServer.create() server.respondWith //availability/, (xhr) → xhr.respond 200, error: 'no matches' results = new AvailabilitySearch server.respond() after -> server.restore()
  • 24. Fixtures ● Examples of data. ● Can be server responses, database rows or collection info. ● Normally in JSON format for easy handling. lotsOfBookings = require 'json!spec/fixtures/lots_of_bookings.json' Collection = null before -> collection = new Bookings lotsOfBookings

Editor's Notes

  • #3: It fits on the slides better.
  • #4: Unit = smallest type of test used when looking at a single method of a class. Integration = when several classes are tested whilst working together. Some of our bigger unit tests should be integration tests. Acceptance = test if requirements are met, we use selenium for this, tests involve moving between pages. Manual = ask a tester what they do!
  • #6: Testers should know about the coverage of the first two types.
  • #7: Don't be the one that states “it does not need any tests”. We all should accept that code needs unit tests. Tests do take time to write. Managers can wait for tests. Want to know how a class is used, read the tests.
  • #8: Qunit was used for a small bit of work on hxml, bet no-one has spotted it. Jasmine is used on the tripapp, mainly because it was the best tool at the time. Mocha is used by most other projects. Syntax between jasmine and mocha is almost identical. so....
  • #9: The rest of this talk is about mocha as it has the most features and is the easiest to integrate into CI's using grunt etc.. It also allows asynchronous testing too.
  • #10: Who likes dealing with files with hundreds of lines, classes with lots of tests should be split into multiple files. Don't test internal lines of a method as these will hinder refactoring. Tripapp views: Too big, hard to test Should be testing template data Don't care what setup they do.
  • #11: First describe for the class to be tested 2nd describe for the method being tested. Further describes to group many tests for a method. It's should contain a single assertion for readability, many assertions for a single it will force you to read the stack trace. It's should be a readable sentence “it does something expected.”
  • #12: Split up the assertions
  • #13: If you need to consider different situations then split tests into contexts.
  • #14: Half time! Any questions so far?
  • #15: There is normally a good reason to test code in different situations, one example would be on a different hardware platform. If say we stop supporting android, we could easily remove the redundant context, as we would know that the situation does not need to be tested for anymore. Context descriptions normally start with “when”, “in”, or “with“ With older browsers When logged in In a completed state
  • #16: These are where you should put any setup code for a single or group of tests. Separating any setup logic makes the tests easy to read and maintain. The after methods are used to return any global variables back to normal state before any further tests are run.
  • #17: These all do the same job. There are many different assertions and the most appropriate one should be used for a test.
  • #18: I find chai very readable and this will help new devs understand your tests. Testers could probably understand this syntax too. Words such as “at”, “be”, “have” dont actually do anything they are just for readability.
  • #19: Code that throws exceptions can be tested, by surrounding it in a block and check for the error thrown. The check can be a regex or a exact string match. You can also check if an exception is not thrown.
  • #20: Stubs are very similar but can return set values if need. You can spy on a function and call the original function too. As you can see you need to restore the spied out function after use so other tests get a clean slate. If you are testing methods with callbacks spies can be used here too.
  • #21: Factories make stuff, in application and test code they produces instances of objects with some certain setup.
  • #22: There could be more setup than this, you may have to create several instances of objects in order to create an instance you need to test with.
  • #23: Now this becomes two lines and if the user changes you only need to update it in one place.
  • #24: A fair amount of setup here, this is only needed if the code doing the request can't be stubbed out or if a certain response is needed for testing. The line in bold is the actual method under test which would perform the network request normally.
  • #25: One thing to note here is that any fixture data should not be made my hand but copy/pasted from real network responses or dumps of data. Remember to update fixtures when external data changes, otherwise your tests will not be testing real world responses.