SlideShare a Scribd company logo
β˜…How do I write
Testable Javascript?
β˜…Agenda
β˜…Who Am I?
β˜…State of the Room?
β˜…Ways to test Javascript?
β˜…Different Testing Environments?
β˜…Overview of Testing Tools
β˜…Using Testing in your Workflow
β˜…Spaghetti Javascript
β˜…Refactor Spaghetti into Testable Javascript
β˜…Installing Jasmine + Live Demo
β˜…Who Am I?
β˜…Gavin Pickin – developing Web Apps since late 90s
β—‹Ortus Solutions Software Consultant
β—‹ContentBox Evangelist
β˜…What else do you need to know?
β—‹CFMLRepo.com http://www.cfmlrepo.com
β—‹Blog - http://www.gpickin.com
β—‹Twitter – http://twitter.com/gpickin
β—‹Github - https://github.com/gpickin
β˜…Lets get on with the show.
β˜…State of the Room
β˜… A few questions for you guys
β˜… If you have arms, use them.
β˜…State of the Room
Testing? What’s testing?
β˜…State of the Room
Yeah,
I’ve heard of it.
Why do you
think I’m here?
β˜…State of the Room
Yes I know I should be testing,
but I’m not sure how to do it
β˜…State of the Room
My Boss and my Customers wouldn’t
let me
β˜…State of the Room
I’m a tester
β˜…State of the Room
I’m a test writing ninja
Call me Majano,
Luis Majano
β˜…Ways to Test your Code
β˜…Click around in
the browser yourself
β˜…Setup Selenium / Web Driver to click around for
you
β˜…Structured Programmatic Tests
β˜…Types of Testing
β˜…Types of Testing
β˜…Black/White Box
β˜…Unit Testing
β˜…Integration Testing
β˜…Functional Tests
β˜…System Tests
β˜…End to End Tests
β˜…Sanity Testing
β˜…Regression Test
β˜…Acceptance Tests
β˜…Load Testing
β˜…Stress Test
β˜…Performance Tests
β˜…Usability Tests
β˜…+ More
β˜…Levels of Testing
β˜…Cost of a Bug
The bug will cost one way or another
β˜…Integration Testing
β˜…Integration Testing
β˜…Integration Tests several of the pieces
together
β˜…Most of the types of tests are variations of
an Integration Test
β˜…Can include mocks but can full end to end
tests including DB / APIs
β˜…Unit Testing
β˜…Unit Testing
β€œunit testing is a software verification
and validation method in which a
programmer tests if individual units of
source code are fit for use. A unit is the
smallest testable part of an application”
- wikipedia
β˜…Unit Testing
β˜…Can improve code quality -> quick error
discovery
β˜…Code confidence via immediate
verification
β˜…Can expose high coupling
β˜…Will encourage refactoring to produce >
testable code
β˜…Remember: Testing is all about behavior
and expectations
β˜…Styles – TDD vs BDD
β˜…TDD = Test Driven Development
β—‹Write Tests
β—‹Run them and they Fail
β—‹Write Functions to Fulfill the Tests
β—‹Tests should pass
β—‹Refactor in confidence
β˜…Test focus on Functionality
β˜…Styles – TDD vs BDD
β˜…BDD = Behavior Driven Development
Actually similar to TDD except:
β˜…Focuses on Behavior and Specifications
β˜…Specs (tests) are fluent and readable
β˜…Readability makes them great for all levels of
testing in the organization
β˜…Hard to find TDD examples in JS that are not
using BDD describe and it blocks
β˜…TDD Example
Test( β€˜Email address must not be blank’,
function(){
notEqual(email, β€œβ€, "failed");
});
β˜…BDD Example
Describe( β€˜Email Address’, function(){
It(β€˜should not be blank’, function(){
expect(email).not.toBe(β€œβ€);
});
});
β˜…Matchers
expect(true).toBe(true);
expect(true).toBe(true);
expect(true).toBe(true);
expect(true).toBe(true);
β˜…Matchers
expect(true).not.toBe(true);
expect(true).not.toBe(true);
expect(true).not.toBe(true);
expect(true).not.toBe(true);
expect(true).not.toBe(true);
β˜…Matcher Samples
expect(true).toBe(true);
expect(a).not.toBe(null);
expect(a).toEqual(12);
expect(message).toMatch(/bar/);
expect(message).toMatch("bar");
expect(message).not.toMatch(/quux/);
expect(a.foo).toBeDefined();
expect(a.bar).not.toBeDefined();
β˜…Different Testing
Environments?
NodeJS - CLI In the Browser
β˜…Overview of Testing Tools
β˜…There are a few choices
β˜…Main Testing Players
β˜…Jasmine, Mocha and QUnit
β˜…Jasmine
β˜…Jasmine comes ready to go out of the box
β˜…Fluent Syntax – BDD Style
β˜…Includes lots of matchers
β˜…Has spies included
β˜…Very popular, lots of support
β˜…Angular uses Jasmine with Karma (CLI)
β˜…Headless running and plays well with CI
servers
β˜…Jasmine - Cons
β˜…Async testing in 1.3 can be a
headache
β˜…Expects *spec.js suffix for test files
β—‹This can be modified depending on
how you are running the tests
β˜…Jasmine – Sample Test
describe("Hello world function", function() {
it(”contains the word world", function() {
expect(helloWorld()).toContain("world");
});
});
β˜…Mochaβ˜…Simple Setup
β˜…Simple Async testing
β˜…Works great with other Assertion libraries
like Chai ( not included )
β˜…Solid Support with CI Servers, with Plugins
for others
β˜…Opinion says Mocha blazing the trail for
new features
β˜…Mocha - Cons
β˜…Requires other Libraries for key features
β—‹No Assertion Library included
β—‹No Mocking / Spied included
β—‹Need to create the runner manually
β˜…Newer to the game so not as popular or
supported as others but gaining traction.
β˜…Mocha – BDD Sample Test
var expect = require('chai').expect;
describe(’Hello World Function', function(){
it('should contain the word world', function(){
expect(helloWorld()).to.contain(’world');
})
})
β˜…QUnit
β˜…The oldest of the main testing frameworks
β˜…Is popular due to use in jQuery and age
β˜…Ember’s default Unit testing Framework
β˜…QUnit - Cons
β˜…Development slowed down since
2013 (but still under development)
β˜…Syntax – No BDD style
β˜…Assertion libraries – limited
matchers
β˜…QUnit – Sample Test
QUnit.test( "ok test", function( assert ) {
assert.ok( true, "true succeeds" );
assert.ok( "non-empty", "non-empty string succeeds"
);
assert.ok( false, "false fails" );
assert.ok( 0, "0 fails" );
assert.ok( NaN, "NaN fails" );
assert.ok( "", "empty string fails" );
assert.ok( null, "null fails" );
assert.ok( undefined, "undefined fails" );
});
β˜…Spaghetti Javascript
Photo Credit – Kombination
http://www.kombination.co.za/wp-content/uploads/2012/10/baby_w_spaghetti_mess_4987941.jpg
β˜…Spaghetti Javascript Example
If we have time at the end
β˜…Spaghetti Javascript Example
β˜…Refactoring Spaghetti
β˜…Things to refactor to make your code testable
β—‹Code should not be one big chunk of
Javascript in onReady()
β—‹Deep nested callbacks & Anon functions
cannot easily be singled out and tested
β—‹Remove Tight Coupling – DOM access for
example
β˜…Object Literals
var personObjLit = {
ssn: ’xxxxxxxx',
age: '35',
name: 'Gavin Pickin',
getAge: function(){
return this.age;
},
getName: function() {
return this.name;
}
};
β˜…Module Pattern
var personObjLit2 = function() {
ssn = ’xxxxxxx';
age = '35';
name = 'Gavin Pickin’;
return {
getAge: function(){
return age;
},
getName: function() {
return name;
}
};
};
β˜…Using Testing in your
Workflow
β˜…Using HTML Test Runners
β—‹Keep a Browser open
β—‹F5 refresh tests
β˜…Command Line Tests
β˜…Run Jasmine – manual
β—‹Run tests at the end of each section of work
β˜…Run Grunt-Watch – automatic
β—‹Runs Jasmine on every file change
β—‹Grunt can run other tasks as well,
minification etc
β˜…Testing in your IDE
β˜…Browser Views
β—‹Eclipse allows you to open files in
web view – uses HTML Runner
β˜…Run Jasmine / Grunt / Karma in IDE
Console
β—‹Easy to setup – See Demo– Sublime Text
2
β˜…Live Demo and
Examples
*Install / Run Jasmine Standalone for Browser
*Install / Run Jasmine with NodeJs
*Install/ Run Jasmine with Grunt Watch
*Install / Run Grunt Watch inside Sublime Text 2
β˜…Install / Run Jasmine for In-
Browser Testing
Download standalone package from Github (I have 2.1.3)
https://github.com/jasmine/jasmine/tree/master/dist
Unzip into your /tests folder
Run /tests/SpecRunner.html to see example tests
β˜…Standalone Jasmine
β˜…Installing Jasmine for
in Browser Testing
β˜…SpecRunner Setup
Jasmine Browser Test
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Jasmine Spec Runner v2.1.3</title>
<link rel="shortcut icon" type="image/png" href="lib/jasmine-2.1.3/jasmine_favicon.png">
<link rel="stylesheet" href="lib/jasmine-2.1.3/jasmine.css”>
<script src="lib/jasmine-2.1.3/jasmine.js"></script>
<script src="lib/jasmine-2.1.3/jasmine-html.js"></script>
<script src="lib/jasmine-2.1.3/boot.js"></script>
<!-- include source files here... -->
<script src="../js/services/loginService.js"></script>
<!-- include spec files here... -->
<script src="spec/loginServiceSpec.js"></script>
</head>
<body>
</body>
</html>
β˜…Installing Jasmine
with NodeJS
Assuming you have NodeJs Installed… install Jasmine
$ npm install jasmine
jasmine@2.2.1 node_modules/jasmine
β”œβ”€β”€ exit@0.1.2
β”œβ”€β”€ jasmine-core@2.2.0
└── glob@3.2.11 (inherits@2.0.1, minimatch@0.3.0)
β˜…Installing Jasmine
with NodeJS
Once Jasmine is installed in your project
$ Jasmine init
β˜…Installing Jasmine
with NodeJS
Edit Jasmine.json to update Locations for Spec Files and Helper Files
{
"spec_dir": "spec",
"spec_files": [
"**/*[sS]pec.js"
],
"helpers": [
"helpers/**/*.js"
]
}
β˜…Running Jasmine
Tests with NodeJS$ Jasmine
Started
F
Failures:
1) A suite contains spec with an expectation
Message:
Expected true to be false.
Stack:
Error: Expected true to be false.
at Object.<anonymous>
(/Users/gavinpickin/Dropbox/Apps/testApp/www/spec/test_spec.js:3:
18)
1 spec, 1 failure
Finished in 0.009 seconds
β˜…Running Jasmine
Tests with NodeJS
β˜…Jasmine-Node is great for Node
β˜…Jasmine Node doesn’t have a headless browser
β˜…Hard to test Browser code
β˜…So what should I use?
β˜…Installing Jasmine
with Grunt Watcher
β˜…Install Grunt
npm install grunt
β˜…Install Grunt – Jasmine
npm install grunt-contrib-jasmine
β˜…Install Grunt – Watch
npm install grunt-contrib-watch
β˜…Note: On Mac, I also needed to install Grunt CLI
npm install –g grunt-cli
β˜…Configuring Jasmine
with Grunt Watcher
// gruntfile.js - https://gist.github.com/gpickin/1e1e7902d1d3676d23c5
module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('node_modules/grunt/package.json'),
jasmine: {
all: {
src: ['js/*.js' ],
options: {
//'vendor': ['path/to/vendor/libs/*.js'],
'specs': ['specs/*.js' ]
}
}
},
β˜…Configuring Jasmine
with Grunt Watcher
// gruntfile.js part 2
watch: {
js: {
files: [
'js/*.js',
'specs/*.js',
],
tasks: ['jasmine:all']
}
}
});
β˜…Configuring Jasmine
with Grunt Watcher
// gruntfile.js part 3
grunt.loadNpmTasks('grunt-contrib-jasmine');
grunt.loadNpmTasks('grunt-contrib-watch');
};
β˜…Example Spec Jasmine with
Grunt Watcher
describe("A suite", function() {
it("contains spec with an expectation", function() {
expect(true).toBe(true);
});
});
β˜…Running Jasmine
with Grunt Watcher
β˜…Running Jasmine
with Grunt Watcher
β˜…Running in Sublime Text 2
β˜…Install PackageControl into Sublime Text
β˜…Install Grunt from PackageControl
β—‹https://packagecontrol.io/packages/Grunt
β˜…Update Grunt Sublime Settings for paths
{
"exec_args": { "path": "/bin:/usr/bin:/usr/local/bin” }
}
β˜…Then Command Shift P – grunt
β˜…Running in Sublime Text 2
β˜…Refactoring Spaghetti
β˜…Lets look at some code
β˜…This isn’t BEST PRACTICE, its BETTER
PRACTICE than you were doing
β˜…Its not really refactoring if you don’t have
tests, its
β€œmoving code and asking for trouble”
β˜…Q&A
β˜…Any questions?

More Related Content

PDF
3 WAYS TO TEST YOUR COLDFUSION API
PDF
[CLIW] Web testing
PDF
Developers Testing - Girl Code at bloomon
PDF
Testacular
PDF
AN EXERCISE IN CLEANER CODE - FROM LEGACY TO MAINTAINABLE
PDF
Creating Gradle Plugins - GR8Conf US
PDF
Developer Tests - Things to Know
PPTX
TDD in Go with Ginkgo and Gomega
3 WAYS TO TEST YOUR COLDFUSION API
[CLIW] Web testing
Developers Testing - Girl Code at bloomon
Testacular
AN EXERCISE IN CLEANER CODE - FROM LEGACY TO MAINTAINABLE
Creating Gradle Plugins - GR8Conf US
Developer Tests - Things to Know
TDD in Go with Ginkgo and Gomega

What's hot (18)

PDF
ES3-2020-P2 Bowling Game Kata
PPTX
Test your user interface using BDD (Swedish)
Β 
PPTX
Ten Man-Years of JavaFX: Real World Project Experiences
PDF
Mykhailo Bodnarchuk "The history of the Codeception project"
Β 
PDF
QA 4 python
PDF
Develop Maintainable Apps
PDF
Creating Gradle Plugins
PDF
How do I write Testable Javascript
PDF
How do I write Testable Javascript?
PDF
Java Beginners Meetup February 2017: Testing and TDD
PDF
TDD and Simple Design Workshop - Session 1 - March 2019
PDF
Selenium camp v1
PDF
Test Driven Development
PDF
High Performance JavaScript 2011
PDF
Night Watch with QA
PDF
Refactoring Legacy Code
PDF
Ruby onrails cucumber-rspec-capybara
PDF
Automated testing in Drupal
ES3-2020-P2 Bowling Game Kata
Test your user interface using BDD (Swedish)
Β 
Ten Man-Years of JavaFX: Real World Project Experiences
Mykhailo Bodnarchuk "The history of the Codeception project"
Β 
QA 4 python
Develop Maintainable Apps
Creating Gradle Plugins
How do I write Testable Javascript
How do I write Testable Javascript?
Java Beginners Meetup February 2017: Testing and TDD
TDD and Simple Design Workshop - Session 1 - March 2019
Selenium camp v1
Test Driven Development
High Performance JavaScript 2011
Night Watch with QA
Refactoring Legacy Code
Ruby onrails cucumber-rspec-capybara
Automated testing in Drupal
Ad

Similar to How do I write Testable Javascript - Presented at dev.Objective() June 16, 2016 (20)

PDF
BDD Testing and Automating from the trenches - Presented at Into The Box June...
PDF
ITB2016 -BDD testing and automation from the trenches
PDF
3 WAYS TO TEST YOUR COLDFUSION API -
PPTX
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
PDF
Developer Tests - Things to Know (Vilnius JUG)
PDF
North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017
PDF
Test driven development_continuous_integration
ODP
2014 11 20 Drupal 7 -> 8 test migratie
PDF
TDD in Python With Pytest
PDF
Hadoop: Big Data Stacks validation w/ iTest How to tame the elephant?
PDF
Quick tour to front end unit testing using jasmine
PDF
Writing Tests with the Unity Test Framework
PDF
Das Frontend richtig Testen – mit Jest @Developer Week 2018
PDF
Jest: Frontend Testing leicht gemacht @EnterJS2018
PDF
Test and Behaviour Driven Development (TDD/BDD)
PPTX
Understanding JavaScript Testing
PDF
Continuous Integration Testing in Django
ODP
Behat Workshop at WeLovePHP
PDF
Bdd and-testing
PDF
Behaviour Driven Development and Thinking About Testing
Β 
BDD Testing and Automating from the trenches - Presented at Into The Box June...
ITB2016 -BDD testing and automation from the trenches
3 WAYS TO TEST YOUR COLDFUSION API -
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
Developer Tests - Things to Know (Vilnius JUG)
North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017
Test driven development_continuous_integration
2014 11 20 Drupal 7 -> 8 test migratie
TDD in Python With Pytest
Hadoop: Big Data Stacks validation w/ iTest How to tame the elephant?
Quick tour to front end unit testing using jasmine
Writing Tests with the Unity Test Framework
Das Frontend richtig Testen – mit Jest @Developer Week 2018
Jest: Frontend Testing leicht gemacht @EnterJS2018
Test and Behaviour Driven Development (TDD/BDD)
Understanding JavaScript Testing
Continuous Integration Testing in Django
Behat Workshop at WeLovePHP
Bdd and-testing
Behaviour Driven Development and Thinking About Testing
Β 
Ad

More from Gavin Pickin (8)

PDF
Itb 2021 - Bulding Quick APIs by Gavin Pickin
PPTX
Containerizing ContentBox CMS
PPTX
ColdBox APIs + VueJS - powering Mobile, Desktop and Web Apps with 1 VueJS cod...
PDF
Take home your very own free Vagrant CFML Dev Environment - Presented at dev....
PPTX
How do I write Testable Javascript so I can Test my CF API on Server and Client
PDF
Just Mock It - Mocks and Stubs
PDF
Getting your Hooks into Cordova
PDF
Setting up your Multi Engine Environment - Apache Railo and ColdFusion
Itb 2021 - Bulding Quick APIs by Gavin Pickin
Containerizing ContentBox CMS
ColdBox APIs + VueJS - powering Mobile, Desktop and Web Apps with 1 VueJS cod...
Take home your very own free Vagrant CFML Dev Environment - Presented at dev....
How do I write Testable Javascript so I can Test my CF API on Server and Client
Just Mock It - Mocks and Stubs
Getting your Hooks into Cordova
Setting up your Multi Engine Environment - Apache Railo and ColdFusion

Recently uploaded (20)

PPTX
INTERNET------BASICS-------UPDATED PPT PRESENTATION
PPTX
Job_Card_System_Styled_lorem_ipsum_.pptx
PPTX
presentation_pfe-universite-molay-seltan.pptx
PDF
πŸ’° π”πŠπ“πˆ πŠπ„πŒπ„ππ€ππ†π€π πŠπˆππ„π‘πŸ’πƒ π‡π€π‘πˆ 𝐈𝐍𝐈 πŸπŸŽπŸπŸ“ πŸ’°
Β 
PPT
FIRE PREVENTION AND CONTROL PLAN- LUS.FM.MQ.OM.UTM.PLN.00014.ppt
PPTX
Funds Management Learning Material for Beg
PPTX
international classification of diseases ICD-10 review PPT.pptx
PPTX
artificialintelligenceai1-copy-210604123353.pptx
Β 
PPT
isotopes_sddsadsaadasdasdasdasdsa1213.ppt
PPTX
introduction about ICD -10 & ICD-11 ppt.pptx
PDF
Introduction to the IoT system, how the IoT system works
PPTX
June-4-Sermon-Powerpoint.pptx USE THIS FOR YOUR MOTIVATION
PPTX
Power Point - Lesson 3_2.pptx grad school presentation
Β 
PDF
FINAL CALL-6th International Conference on Networks & IOT (NeTIOT 2025)
PPTX
Mathew Digital SEO Checklist Guidlines 2025
PPTX
522797556-Unit-2-Temperature-measurement-1-1.pptx
PPTX
artificial intelligence overview of it and more
PPTX
innovation process that make everything different.pptx
PDF
Unit-1 introduction to cyber security discuss about how to secure a system
PDF
Exploring VPS Hosting Trends for SMBs in 2025
INTERNET------BASICS-------UPDATED PPT PRESENTATION
Job_Card_System_Styled_lorem_ipsum_.pptx
presentation_pfe-universite-molay-seltan.pptx
πŸ’° π”πŠπ“πˆ πŠπ„πŒπ„ππ€ππ†π€π πŠπˆππ„π‘πŸ’πƒ π‡π€π‘πˆ 𝐈𝐍𝐈 πŸπŸŽπŸπŸ“ πŸ’°
Β 
FIRE PREVENTION AND CONTROL PLAN- LUS.FM.MQ.OM.UTM.PLN.00014.ppt
Funds Management Learning Material for Beg
international classification of diseases ICD-10 review PPT.pptx
artificialintelligenceai1-copy-210604123353.pptx
Β 
isotopes_sddsadsaadasdasdasdasdsa1213.ppt
introduction about ICD -10 & ICD-11 ppt.pptx
Introduction to the IoT system, how the IoT system works
June-4-Sermon-Powerpoint.pptx USE THIS FOR YOUR MOTIVATION
Power Point - Lesson 3_2.pptx grad school presentation
Β 
FINAL CALL-6th International Conference on Networks & IOT (NeTIOT 2025)
Mathew Digital SEO Checklist Guidlines 2025
522797556-Unit-2-Temperature-measurement-1-1.pptx
artificial intelligence overview of it and more
innovation process that make everything different.pptx
Unit-1 introduction to cyber security discuss about how to secure a system
Exploring VPS Hosting Trends for SMBs in 2025

How do I write Testable Javascript - Presented at dev.Objective() June 16, 2016