SlideShare a Scribd company logo
1 of 58
Download to read offline
* 
* 
* 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

The Screenplay Pattern: Better Interactions for Better Automation
The Screenplay Pattern: Better Interactions for Better AutomationThe Screenplay Pattern: Better Interactions for Better Automation
The Screenplay Pattern: Better Interactions for Better AutomationApplitools
 
Adventures In JavaScript Testing
Adventures In JavaScript TestingAdventures In JavaScript Testing
Adventures In JavaScript TestingThomas Fuchs
 
High Performance JavaScript 2011
High Performance JavaScript 2011High Performance JavaScript 2011
High Performance JavaScript 2011Nicholas Zakas
 
Automated Frontend Testing
Automated Frontend TestingAutomated Frontend Testing
Automated Frontend TestingNeil Crosby
 
ES3-2020-P3 TDD Calculator
ES3-2020-P3 TDD CalculatorES3-2020-P3 TDD Calculator
ES3-2020-P3 TDD CalculatorDavid Rodenas
 
Easy tests with Selenide and Easyb
Easy tests with Selenide and EasybEasy tests with Selenide and Easyb
Easy tests with Selenide and EasybIakiv Kramarenko
 
Developer Tests - Things to Know
Developer Tests - Things to KnowDeveloper Tests - Things to Know
Developer Tests - Things to KnowVaidas Pilkauskas
 
Testing Ext JS and Sencha Touch
Testing Ext JS and Sencha TouchTesting Ext JS and Sencha Touch
Testing Ext JS and Sencha TouchMats Bryntse
 
Testing React Applications
Testing React ApplicationsTesting React Applications
Testing React Applicationsstbaechler
 
Enhance react app with patterns - part 1: higher order component
Enhance react app with patterns - part 1: higher order componentEnhance react app with patterns - part 1: higher order component
Enhance react app with patterns - part 1: higher order componentYao Nien Chung
 
Testing Web Applications
Testing Web ApplicationsTesting Web Applications
Testing Web ApplicationsSeth McLaughlin
 
Test automation & Seleniun by oren rubin
Test automation & Seleniun by oren rubinTest automation & Seleniun by oren rubin
Test automation & Seleniun by oren rubinOren Rubin
 
Web ui tests examples with selenide, nselene, selene & capybara
Web ui tests examples with  selenide, nselene, selene & capybaraWeb ui tests examples with  selenide, nselene, selene & capybara
Web ui tests examples with selenide, nselene, selene & capybaraIakiv Kramarenko
 
Selenide Alternative in Practice - Implementation & Lessons learned [Selenium...
Selenide Alternative in Practice - Implementation & Lessons learned [Selenium...Selenide Alternative in Practice - Implementation & Lessons learned [Selenium...
Selenide Alternative in Practice - Implementation & Lessons learned [Selenium...Iakiv Kramarenko
 
Kiss PageObjects [01-2017]
Kiss PageObjects [01-2017]Kiss PageObjects [01-2017]
Kiss PageObjects [01-2017]Iakiv Kramarenko
 

What's hot (19)

The Screenplay Pattern: Better Interactions for Better Automation
The Screenplay Pattern: Better Interactions for Better AutomationThe Screenplay Pattern: Better Interactions for Better Automation
The Screenplay Pattern: Better Interactions for Better Automation
 
Adventures In JavaScript Testing
Adventures In JavaScript TestingAdventures In JavaScript Testing
Adventures In JavaScript Testing
 
High Performance JavaScript 2011
High Performance JavaScript 2011High Performance JavaScript 2011
High Performance JavaScript 2011
 
Automated Frontend Testing
Automated Frontend TestingAutomated Frontend Testing
Automated Frontend Testing
 
Testacular
TestacularTestacular
Testacular
 
ES3-2020-P3 TDD Calculator
ES3-2020-P3 TDD CalculatorES3-2020-P3 TDD Calculator
ES3-2020-P3 TDD Calculator
 
Easy tests with Selenide and Easyb
Easy tests with Selenide and EasybEasy tests with Selenide and Easyb
Easy tests with Selenide and Easyb
 
Developer Tests - Things to Know
Developer Tests - Things to KnowDeveloper Tests - Things to Know
Developer Tests - Things to Know
 
Protractor Training in Pune by QuickITDotnet
Protractor Training in Pune by QuickITDotnet Protractor Training in Pune by QuickITDotnet
Protractor Training in Pune by QuickITDotnet
 
Testing Ext JS and Sencha Touch
Testing Ext JS and Sencha TouchTesting Ext JS and Sencha Touch
Testing Ext JS and Sencha Touch
 
Testing React Applications
Testing React ApplicationsTesting React Applications
Testing React Applications
 
Enhance react app with patterns - part 1: higher order component
Enhance react app with patterns - part 1: higher order componentEnhance react app with patterns - part 1: higher order component
Enhance react app with patterns - part 1: higher order component
 
Testing Web Applications
Testing Web ApplicationsTesting Web Applications
Testing Web Applications
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
Test automation & Seleniun by oren rubin
Test automation & Seleniun by oren rubinTest automation & Seleniun by oren rubin
Test automation & Seleniun by oren rubin
 
Code ceptioninstallation
Code ceptioninstallationCode ceptioninstallation
Code ceptioninstallation
 
Web ui tests examples with selenide, nselene, selene & capybara
Web ui tests examples with  selenide, nselene, selene & capybaraWeb ui tests examples with  selenide, nselene, selene & capybara
Web ui tests examples with selenide, nselene, selene & capybara
 
Selenide Alternative in Practice - Implementation & Lessons learned [Selenium...
Selenide Alternative in Practice - Implementation & Lessons learned [Selenium...Selenide Alternative in Practice - Implementation & Lessons learned [Selenium...
Selenide Alternative in Practice - Implementation & Lessons learned [Selenium...
 
Kiss PageObjects [01-2017]
Kiss PageObjects [01-2017]Kiss PageObjects [01-2017]
Kiss PageObjects [01-2017]
 

Similar to How do I write testable javascript?

How do I write Testable Javascript so I can Test my CF API on Server and Client
How do I write Testable Javascript so I can Test my CF API on Server and ClientHow do I write Testable Javascript so I can Test my CF API on Server and Client
How do I write Testable Javascript so I can Test my CF API on Server and ClientGavin Pickin
 
How do I Write Testable Javascript so I can Test my CF API on Server and Client
How do I Write Testable Javascript so I can Test my CF API on Server and ClientHow do I Write Testable Javascript so I can Test my CF API on Server and Client
How do I Write Testable Javascript so I can Test my CF API on Server and ClientColdFusionConference
 
Javascript unit testing, yes we can e big
Javascript unit testing, yes we can   e bigJavascript unit testing, yes we can   e big
Javascript unit testing, yes we can e bigAndy Peterson
 
3 WAYS TO TEST YOUR COLDFUSION API -
3 WAYS TO TEST YOUR COLDFUSION API - 3 WAYS TO TEST YOUR COLDFUSION API -
3 WAYS TO TEST YOUR COLDFUSION API - Ortus Solutions, Corp
 
3 WAYS TO TEST YOUR COLDFUSION API
3 WAYS TO TEST YOUR COLDFUSION API3 WAYS TO TEST YOUR COLDFUSION API
3 WAYS TO TEST YOUR COLDFUSION APIGavin Pickin
 
North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017
North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017
North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017Ortus Solutions, Corp
 
Testing ASP.NET - Progressive.NET
Testing ASP.NET - Progressive.NETTesting ASP.NET - Progressive.NET
Testing ASP.NET - Progressive.NETBen Hall
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyDavid Padbury
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenerytoddbr
 
Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)vilniusjug
 
Testing in AngularJS
Testing in AngularJSTesting in AngularJS
Testing in AngularJSPeter Drinnan
 
Quick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmineQuick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmineGil Fink
 
ActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group PresentationActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group Presentationipolevoy
 
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 MizrahiRan Mizrahi
 
Effecient javascript
Effecient javascriptEffecient javascript
Effecient javascriptmpnkhan
 
UI Testing Best Practices - An Expected Journey
UI Testing Best Practices - An Expected JourneyUI Testing Best Practices - An Expected Journey
UI Testing Best Practices - An Expected JourneyOren Farhi
 
JavaScript performance patterns
JavaScript performance patternsJavaScript performance patterns
JavaScript performance patternsStoyan Stefanov
 
Keep your Wicket application in production
Keep your Wicket application in productionKeep your Wicket application in production
Keep your Wicket application in productionMartijn Dashorst
 

Similar to How do I write testable javascript? (20)

How do I write Testable Javascript so I can Test my CF API on Server and Client
How do I write Testable Javascript so I can Test my CF API on Server and ClientHow do I write Testable Javascript so I can Test my CF API on Server and Client
How do I write Testable Javascript so I can Test my CF API on Server and Client
 
How do I Write Testable Javascript so I can Test my CF API on Server and Client
How do I Write Testable Javascript so I can Test my CF API on Server and ClientHow do I Write Testable Javascript so I can Test my CF API on Server and Client
How do I Write Testable Javascript so I can Test my CF API on Server and Client
 
Javascript unit testing, yes we can e big
Javascript unit testing, yes we can   e bigJavascript unit testing, yes we can   e big
Javascript unit testing, yes we can e big
 
3 WAYS TO TEST YOUR COLDFUSION API -
3 WAYS TO TEST YOUR COLDFUSION API - 3 WAYS TO TEST YOUR COLDFUSION API -
3 WAYS TO TEST YOUR COLDFUSION API -
 
3 WAYS TO TEST YOUR COLDFUSION API
3 WAYS TO TEST YOUR COLDFUSION API3 WAYS TO TEST YOUR COLDFUSION API
3 WAYS TO TEST YOUR COLDFUSION API
 
North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017
North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017
North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017
 
Testing ASP.NET - Progressive.NET
Testing ASP.NET - Progressive.NETTesting ASP.NET - Progressive.NET
Testing ASP.NET - Progressive.NET
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenery
 
สปริงเฟรมเวิร์ค4.1
สปริงเฟรมเวิร์ค4.1สปริงเฟรมเวิร์ค4.1
สปริงเฟรมเวิร์ค4.1
 
BDD in iOS with Cedar
BDD in iOS with CedarBDD in iOS with Cedar
BDD in iOS with Cedar
 
Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)
 
Testing in AngularJS
Testing in AngularJSTesting in AngularJS
Testing in AngularJS
 
Quick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmineQuick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmine
 
ActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group PresentationActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group Presentation
 
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
 
Effecient javascript
Effecient javascriptEffecient javascript
Effecient javascript
 
UI Testing Best Practices - An Expected Journey
UI Testing Best Practices - An Expected JourneyUI Testing Best Practices - An Expected Journey
UI Testing Best Practices - An Expected Journey
 
JavaScript performance patterns
JavaScript performance patternsJavaScript performance patterns
JavaScript performance patterns
 
Keep your Wicket application in production
Keep your Wicket application in productionKeep your Wicket application in production
Keep your Wicket application in production
 

More from devObjective

Raspberry Pi a la CFML
Raspberry Pi a la CFMLRaspberry Pi a la CFML
Raspberry Pi a la CFMLdevObjective
 
Effective version control
Effective version controlEffective version control
Effective version controldevObjective
 
Front end-modernization
Front end-modernizationFront end-modernization
Front end-modernizationdevObjective
 
Using type script to build better apps
Using type script to build better appsUsing type script to build better apps
Using type script to build better appsdevObjective
 
Csp and http headers
Csp and http headersCsp and http headers
Csp and http headersdevObjective
 
Who owns Software Security
Who owns Software SecurityWho owns Software Security
Who owns Software SecuritydevObjective
 
Naked and afraid Offline mobile
Naked and afraid Offline mobileNaked and afraid Offline mobile
Naked and afraid Offline mobiledevObjective
 
Web hackingtools 2015
Web hackingtools 2015Web hackingtools 2015
Web hackingtools 2015devObjective
 
Node without servers aws-lambda
Node without servers aws-lambdaNode without servers aws-lambda
Node without servers aws-lambdadevObjective
 
Garbage First and You!
Garbage First and You!Garbage First and You!
Garbage First and You!devObjective
 
Paying off emotional debt
Paying off emotional debtPaying off emotional debt
Paying off emotional debtdevObjective
 
My SQL Skills Killed the Server
My SQL Skills Killed the ServerMy SQL Skills Killed the Server
My SQL Skills Killed the ServerdevObjective
 
Authentication Control
Authentication ControlAuthentication Control
Authentication ControldevObjective
 
Multiply like rabbits with rabbit mq
Multiply like rabbits with rabbit mqMultiply like rabbits with rabbit mq
Multiply like rabbits with rabbit mqdevObjective
 
Intro to TDD & BDD
Intro to TDD & BDDIntro to TDD & BDD
Intro to TDD & BDDdevObjective
 

More from devObjective (20)

Lets git together
Lets git togetherLets git together
Lets git together
 
Raspberry Pi a la CFML
Raspberry Pi a la CFMLRaspberry Pi a la CFML
Raspberry Pi a la CFML
 
Command box
Command boxCommand box
Command box
 
Effective version control
Effective version controlEffective version control
Effective version control
 
Front end-modernization
Front end-modernizationFront end-modernization
Front end-modernization
 
Using type script to build better apps
Using type script to build better appsUsing type script to build better apps
Using type script to build better apps
 
Csp and http headers
Csp and http headersCsp and http headers
Csp and http headers
 
Who owns Software Security
Who owns Software SecurityWho owns Software Security
Who owns Software Security
 
Naked and afraid Offline mobile
Naked and afraid Offline mobileNaked and afraid Offline mobile
Naked and afraid Offline mobile
 
Web hackingtools 2015
Web hackingtools 2015Web hackingtools 2015
Web hackingtools 2015
 
Node without servers aws-lambda
Node without servers aws-lambdaNode without servers aws-lambda
Node without servers aws-lambda
 
I am-designer
I am-designerI am-designer
I am-designer
 
Garbage First and You!
Garbage First and You!Garbage First and You!
Garbage First and You!
 
Fusion Reactor
Fusion ReactorFusion Reactor
Fusion Reactor
 
Paying off emotional debt
Paying off emotional debtPaying off emotional debt
Paying off emotional debt
 
My SQL Skills Killed the Server
My SQL Skills Killed the ServerMy SQL Skills Killed the Server
My SQL Skills Killed the Server
 
Authentication Control
Authentication ControlAuthentication Control
Authentication Control
 
Multiply like rabbits with rabbit mq
Multiply like rabbits with rabbit mqMultiply like rabbits with rabbit mq
Multiply like rabbits with rabbit mq
 
Preso slidedeck
Preso slidedeckPreso slidedeck
Preso slidedeck
 
Intro to TDD & BDD
Intro to TDD & BDDIntro to TDD & BDD
Intro to TDD & BDD
 

Recently uploaded

The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 

Recently uploaded (20)

The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 

How do I write testable javascript?

  • 2. *  * 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
  • 3. *  * 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.
  • 4. *  * A few questions for you guys * If you have arms, use them.
  • 5. *  * Click around in the browser yourself * Setup Selenium / Web Driver to click around for you * Structured Programmatic Tests
  • 6. *  * 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
  • 7. *  * 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
  • 8. *  “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
  • 9. *  * 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
  • 10. *  * 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
  • 11. *  * 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
  • 12. *  Test( ‘Email address must not be blank’, function(){ notEqual(email, “”, "failed"); });
  • 13. *  Describe( ‘Email Address’, function(){ It(‘should not be blank’, function(){ expect(email).not.toBe(“”); }); });
  • 17. *  NodeJS - CLI In the Browser
  • 18. *  * There are a few choices
  • 20. *  * 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
  • 21. *  * 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
  • 22. *  describe("Hello world function", function() { it(”contains the word world", function() { expect(helloWorld()).toContain("world"); }); });
  • 23. *  * 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
  • 24. *  * 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.
  • 25. *  var expect = require('chai').expect; describe(’Hello World Function', function(){ it('should contain the word world', function(){ expect(helloWorld()).to.contain(’world'); }) })
  • 26. *  * The oldest of the main testing frameworks * Is popular due to use in jQuery and age * Ember’s default Unit testing Framework
  • 27. *  * Development slowed down since 2013 (but still under development) * Syntax – No BDD style * Assertion libraries – limited matchers
  • 28. *  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" ); });
  • 29. *  Photo Credit – Kombination http://www.kombination.co.za/wp-content/uploads/2012/10/baby_w_spaghetti_mess_4987941.jpg
  • 30. * 
  • 31. * 
  • 32. *  * 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
  • 33. *  * 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”
  • 34. *  var personObjLit = { ssn: ’xxxxxxxx', age: '35', name: 'Gavin Pickin', getAge: function(){ return this.age; }, getName: function() { return this.name; } };
  • 35. *  var personObjLit2 = function() { ssn = ’xxxxxxx'; age = '35'; name = 'Gavin Pickin’; return { getAge: function(){ return age; }, getName: function() { return name; } }; };
  • 36. *  * Using HTML Test Runners * Keep a Browser open * F5 refresh tests
  • 37. *  * 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
  • 38. *  * 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
  • 39. *  * 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
  • 40. *  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
  • 41. * 
  • 42. * 
  • 43. *  <!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>
  • 44. *  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)
  • 45. *  Once Jasmine is installed in your project $ Jasmine init
  • 46. *  Edit Jasmine.json to update Locations for Spec Files and Helper Files { "spec_dir": "spec", "spec_files": [ "**/*[sS]pec.js" ], "helpers": [ "helpers/**/*.js" ] }
  • 47. *  $ 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
  • 48. *  * Jasmine-Node is great for Node * Jasmine Node doesn’t have a headless browser * Hard to test Browser code * So what should I use?
  • 49. *  * 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
  • 50. *  // 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' ] } } },
  • 51. *  // gruntfile.js part 2 watch: { js: { files: [ 'js/*.js', 'specs/*.js', ], tasks: ['jasmine:all'] } } });
  • 52. *  // gruntfile.js part 3 grunt.loadNpmTasks('grunt-contrib-jasmine'); grunt.loadNpmTasks('grunt-contrib-watch'); };
  • 53. *  describe("A suite", function() { it("contains spec with an expectation", function() { expect(true).toBe(true); }); });
  • 54. * 
  • 55. * 
  • 56. *  * 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
  • 57. * 
  • 58. *  * 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.