SlideShare a Scribd company logo
* 
* 
* 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
* 
* Gavin Pickin – developing Web Apps since late 90s
* What else do you need to know?
* Blog - http://www.gpickin.com
* Twitter – http://twitter.com/gpickin
* Github - https://github.com/gpickin
* Lets get on with the show.
* 
* A few questions for you guys
* If you have arms, use them.
* 
* Click around in the browser yourself
* Setup Selenium / Web Driver to click
around for you
* Structured Programmatic Tests
* 
* 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
* 
* 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 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
* 
* 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
* 
* 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
* 
* 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
* 
Test( ‘Email address must not be
blank’, function(){
notEqual(email, “”, "failed");
});
* 
Describe( ‘Email Address’,
function(){
It(‘should not be blank’, function(){
expect(email).not.toBe(“”);
});
});
* 
expect(true).toBe(true);
expect(true).toBe(true);
expect(true).toBe(true);
expect(true).toBe(true);
* 
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);
* 
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();
* 
NodeJS - CLI In the Browser
* 
* There are a few choices
* 
* Jasmine, Mocha and QUnit
* 
* 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
* 
* 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
* 
describe("Hello world function", function() {
it(”contains the word world", function() {
expect(helloWorld()).toContain("world");
});
});
* 
* 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
* 
* 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.
* 
var expect = require('chai').expect;
describe(’Hello World Function', function(){
it('should contain the word world', function(){
expect(helloWorld()).to.contain(’world');
})
})
* 
* The oldest of the main testing frameworks
* Is popular due to use in jQuery and age
* Ember’s default Unit testing Framework
* 
* Development slowed down since
2013 (but still under development)
* Syntax – No BDD style
* Assertion libraries – limited
matchers
* 
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" );
});
* 
Photo Credit – Kombination
http://www.kombination.co.za/wp-content/uploads/2012/10/baby_w_spaghetti_mess_4987941.jpg
* 
* 
* 
* 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
* 
* 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”
* 
var personObjLit = {
ssn: ’xxxxxxxx',
age: '35',
name: 'Gavin Pickin',
getAge: function(){
return this.age;
},
getName: function() {
return this.name;
}
};
* 
var personObjLit2 = function() {
ssn = ’xxxxxxx';
age = '35';
name = 'Gavin Pickin’;
return {
getAge: function(){
return age;
},
getName: function() {
return name;
}
};
};
* 
* Using HTML Test Runners
* Keep a Browser open
* F5 refresh 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
* 
* 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
* 
* 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
* 
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
* 
* 
* 
<!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>
* 
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)
* 
Once Jasmine is installed in your project
$ Jasmine init
* 
Edit Jasmine.json to update Locations for Spec Files and Helper Files
{
"spec_dir": "spec",
"spec_files": [
"**/*[sS]pec.js"
],
"helpers": [
"helpers/**/*.js"
]
}
* 
$ 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
* 
* Jasmine-Node is great for Node
* Jasmine Node doesn’t have a headless browser
* Hard to test Browser code
* So what should I use?
* 
* 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
* 
// 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' ]
}
}
},
* 
// gruntfile.js part 2
watch: {
js: {
files: [
'js/*.js',
'specs/*.js',
],
tasks: ['jasmine:all']
}
}
});
* 
// gruntfile.js part 3
grunt.loadNpmTasks('grunt-contrib-jasmine');
grunt.loadNpmTasks('grunt-contrib-watch');
};
* 
describe("A suite", function() {
it("contains spec with an expectation", function() {
expect(true).toBe(true);
});
});
* 
* 
* 
* 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
* 
* 
* Any questions?
* Come check out my Cordova Hooks session and see
how you can run Unit Tests (and much more)
whenever you’re preparing a build for your cordova
app.

More Related Content

What's hot (19)

PPTX
The Screenplay Pattern: Better Interactions for Better Automation
Applitools
 
PDF
Adventures In JavaScript Testing
Thomas Fuchs
 
PDF
High Performance JavaScript 2011
Nicholas Zakas
 
ZIP
Automated Frontend Testing
Neil Crosby
 
PDF
Testacular
James Ford
 
PDF
ES3-2020-P3 TDD Calculator
David Rodenas
 
PDF
Easy tests with Selenide and Easyb
Iakiv Kramarenko
 
PDF
Developer Tests - Things to Know
Vaidas Pilkauskas
 
PPTX
Protractor Training in Pune by QuickITDotnet
QuickITDotNet Training and Services
 
PPTX
Testing Ext JS and Sencha Touch
Mats Bryntse
 
PPTX
Testing React Applications
stbaechler
 
PDF
Enhance react app with patterns - part 1: higher order component
Yao Nien Chung
 
PDF
Testing Web Applications
Seth McLaughlin
 
PDF
Backbone.js
Omnia Helmi
 
PDF
Test automation & Seleniun by oren rubin
Oren Rubin
 
PPTX
Code ceptioninstallation
Andrii Lagovskiy
 
PDF
Web ui tests examples with selenide, nselene, selene & capybara
Iakiv Kramarenko
 
PDF
Selenide Alternative in Practice - Implementation & Lessons learned [Selenium...
Iakiv Kramarenko
 
PDF
Kiss PageObjects [01-2017]
Iakiv Kramarenko
 
The Screenplay Pattern: Better Interactions for Better Automation
Applitools
 
Adventures In JavaScript Testing
Thomas Fuchs
 
High Performance JavaScript 2011
Nicholas Zakas
 
Automated Frontend Testing
Neil Crosby
 
Testacular
James Ford
 
ES3-2020-P3 TDD Calculator
David Rodenas
 
Easy tests with Selenide and Easyb
Iakiv Kramarenko
 
Developer Tests - Things to Know
Vaidas Pilkauskas
 
Protractor Training in Pune by QuickITDotnet
QuickITDotNet Training and Services
 
Testing Ext JS and Sencha Touch
Mats Bryntse
 
Testing React Applications
stbaechler
 
Enhance react app with patterns - part 1: higher order component
Yao Nien Chung
 
Testing Web Applications
Seth McLaughlin
 
Backbone.js
Omnia Helmi
 
Test automation & Seleniun by oren rubin
Oren Rubin
 
Code ceptioninstallation
Andrii Lagovskiy
 
Web ui tests examples with selenide, nselene, selene & capybara
Iakiv Kramarenko
 
Selenide Alternative in Practice - Implementation & Lessons learned [Selenium...
Iakiv Kramarenko
 
Kiss PageObjects [01-2017]
Iakiv Kramarenko
 

Viewers also liked (8)

PDF
The curious Life of JavaScript - Talk at SI-SE 2015
jbandi
 
PDF
Chatbot Meetup
Luca Bianchi
 
PDF
Designing a Conversational Intelligent Bot which can cook
Kaushik Das
 
PPTX
Conversational UI, chatbot, AI - simply explained
Daniil Lanovyi
 
PDF
101 Conversational User Interfaces
Redweb Ltd
 
PDF
Messengers, Bots and Personal Assistants
Konstantin Savenkov
 
PDF
Build your first messenger bot
Nowa Labs Pte Ltd
 
PPTX
Chatbot ppt
Geff Thomas
 
The curious Life of JavaScript - Talk at SI-SE 2015
jbandi
 
Chatbot Meetup
Luca Bianchi
 
Designing a Conversational Intelligent Bot which can cook
Kaushik Das
 
Conversational UI, chatbot, AI - simply explained
Daniil Lanovyi
 
101 Conversational User Interfaces
Redweb Ltd
 
Messengers, Bots and Personal Assistants
Konstantin Savenkov
 
Build your first messenger bot
Nowa Labs Pte Ltd
 
Chatbot ppt
Geff Thomas
 
Ad

Similar to How do I write Testable Javascript? (20)

PDF
How to write Testable Javascript
ColdFusionConference
 
PDF
How do I write Testable Javascript - Presented at dev.Objective() June 16, 2016
Gavin Pickin
 
PDF
How do I Write Testable Javascript so I can Test my CF API on Server and Client
ColdFusionConference
 
PDF
3 WAYS TO TEST YOUR COLDFUSION API
Gavin Pickin
 
PDF
3 WAYS TO TEST YOUR COLDFUSION API -
Ortus Solutions, Corp
 
PPTX
How do I write Testable Javascript so I can Test my CF API on Server and Client
Gavin Pickin
 
PDF
Intro To JavaScript Unit Testing - Ran Mizrahi
Ran Mizrahi
 
PDF
Intro to JavaScript Testing
Ran Mizrahi
 
PDF
JavaScript TDD with Jasmine and Karma
Christopher Bartling
 
PDF
Quick tour to front end unit testing using jasmine
Gil Fink
 
PDF
JavaScript Test-Driven Development with Jasmine 2.0 and Karma
Christopher Bartling
 
PDF
BDD Testing and Automating from the trenches - Presented at Into The Box June...
Gavin Pickin
 
PDF
ITB2016 -BDD testing and automation from the trenches
Ortus Solutions, Corp
 
PDF
Reliable Javascript
Glenn Stovall
 
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
 
PDF
Front end unit testing using jasmine
Gil Fink
 
PDF
Node.js Development Workflow Automation with Grunt.js
kiyanwang
 
PDF
JS Lab`16. Сергей Селецкий: "Ретроспектива тестирования JavaScript"
GeeksLab Odessa
 
PDF
JAVASCRIPT Test Driven Development & Jasmine
Anup Singh
 
How to write Testable Javascript
ColdFusionConference
 
How do I write Testable Javascript - Presented at dev.Objective() June 16, 2016
Gavin Pickin
 
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
 
How do I write Testable Javascript so I can Test my CF API on Server and Client
Gavin Pickin
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Ran Mizrahi
 
Intro to JavaScript Testing
Ran Mizrahi
 
JavaScript TDD with Jasmine and Karma
Christopher Bartling
 
Quick tour to front end unit testing using jasmine
Gil Fink
 
JavaScript Test-Driven Development with Jasmine 2.0 and Karma
Christopher Bartling
 
BDD Testing and Automating from the trenches - Presented at Into The Box June...
Gavin Pickin
 
ITB2016 -BDD testing and automation from the trenches
Ortus Solutions, Corp
 
Reliable Javascript
Glenn Stovall
 
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
 
Front end unit testing using jasmine
Gil Fink
 
Node.js Development Workflow Automation with Grunt.js
kiyanwang
 
JS Lab`16. Сергей Селецкий: "Ретроспектива тестирования JavaScript"
GeeksLab Odessa
 
JAVASCRIPT Test Driven Development & Jasmine
Anup Singh
 
Ad

More from Gavin Pickin (8)

PDF
Itb 2021 - Bulding Quick APIs by Gavin Pickin
Gavin Pickin
 
PPTX
Containerizing ContentBox CMS
Gavin Pickin
 
PPTX
ColdBox APIs + VueJS - powering Mobile, Desktop and Web Apps with 1 VueJS cod...
Gavin Pickin
 
PDF
AN EXERCISE IN CLEANER CODE - FROM LEGACY TO MAINTAINABLE
Gavin Pickin
 
PDF
Take home your very own free Vagrant CFML Dev Environment - Presented at dev....
Gavin Pickin
 
PDF
Just Mock It - Mocks and Stubs
Gavin Pickin
 
PDF
Getting your Hooks into Cordova
Gavin Pickin
 
PDF
Setting up your Multi Engine Environment - Apache Railo and ColdFusion
Gavin Pickin
 
Itb 2021 - Bulding Quick APIs by Gavin Pickin
Gavin Pickin
 
Containerizing ContentBox CMS
Gavin Pickin
 
ColdBox APIs + VueJS - powering Mobile, Desktop and Web Apps with 1 VueJS cod...
Gavin Pickin
 
AN EXERCISE IN CLEANER CODE - FROM LEGACY TO MAINTAINABLE
Gavin Pickin
 
Take home your very own free Vagrant CFML Dev Environment - Presented at dev....
Gavin Pickin
 
Just Mock It - Mocks and Stubs
Gavin Pickin
 
Getting your Hooks into Cordova
Gavin Pickin
 
Setting up your Multi Engine Environment - Apache Railo and ColdFusion
Gavin Pickin
 

Recently uploaded (20)

PPTX
How Apagen Empowered an EPC Company with Engineering ERP Software
SatishKumar2651
 
PDF
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
PPTX
Equipment Management Software BIS Safety UK.pptx
BIS Safety Software
 
PDF
Beyond Binaries: Understanding Diversity and Allyship in a Global Workplace -...
Imma Valls Bernaus
 
PDF
Executive Business Intelligence Dashboards
vandeslie24
 
PPTX
Platform for Enterprise Solution - Java EE5
abhishekoza1981
 
PDF
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
PDF
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
PDF
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
PPTX
An Introduction to ZAP by Checkmarx - Official Version
Simon Bennetts
 
PDF
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
PPTX
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
 
PDF
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
PPTX
Revolutionizing Code Modernization with AI
KrzysztofKkol1
 
PPTX
Tally software_Introduction_Presentation
AditiBansal54083
 
PDF
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
PPTX
Java Native Memory Leaks: The Hidden Villain Behind JVM Performance Issues
Tier1 app
 
PDF
Capcut Pro Crack For PC Latest Version {Fully Unlocked} 2025
hashhshs786
 
PPTX
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
How Apagen Empowered an EPC Company with Engineering ERP Software
SatishKumar2651
 
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
Equipment Management Software BIS Safety UK.pptx
BIS Safety Software
 
Beyond Binaries: Understanding Diversity and Allyship in a Global Workplace -...
Imma Valls Bernaus
 
Executive Business Intelligence Dashboards
vandeslie24
 
Platform for Enterprise Solution - Java EE5
abhishekoza1981
 
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
An Introduction to ZAP by Checkmarx - Official Version
Simon Bennetts
 
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
 
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
Revolutionizing Code Modernization with AI
KrzysztofKkol1
 
Tally software_Introduction_Presentation
AditiBansal54083
 
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
Java Native Memory Leaks: The Hidden Villain Behind JVM Performance Issues
Tier1 app
 
Capcut Pro Crack For PC Latest Version {Fully Unlocked} 2025
hashhshs786
 
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 

How do I write Testable Javascript?