SlideShare a Scribd company logo
JavaScript Unit Testing
2012 Mats Bryntse
@bryntum
var me = {
name : ”Mats Bryntse”,
age : 35,
from : ”Helsingborg, Sweden”,
does : ”Runs Bryntum”,
site : ” www.bryntum.com”,
twitter : ”@bryntum”,
likes : ”Ext JS”
};
About me
What we do
JavaScript scheduling
and Gantt charts
Siesta (JS Test Tool)
</SELFPROMOTION>
First, a quick survey:
How many of you...
• have a web application a frontend test suite?
• have frontend test suite as part of your CI proc.
• run your test suite in all major browsers?
• have zero or less frontend tests for your app.
How many of you...
Unit test JS, really?? But...
”... my code is bug free”
”...testing takes time away from
adding new features (+ new bugs)”
”...it’s QA’s job to test”
”... it’s boring and I’ll quit my job”
Reasons for testing
JavaScript
A typical web app...
Interwebs
http://www.app.com
The backend
• Single controlled platform
• Simple to test and refactor
• Good IDEs and tools
C#
Java
PHP
The frontend
• Multiple platforms & versions
(Mac, Windows XP/Vista/7, Linux...)
• Multiple browser versions
• Hard to refactor
• JavaScript support in IDEs is
still !== awesome
Conclusion
• Developing frontend code is harder than
developing server code.
• Mainly due to lack of good tools
• Lots of uncertainty, x-browser issues
• IE6
As good JS dev tools are hard to find, we need to
make good use of existing tools and practices.
Reasons for testing
JavaScript contd.
Easy to introduce
unforeseen errors
isUserCrazy: function(user, isAdmin) {
// DON’T CHANGE THIS
if (user.age > 35 &&
isAdmin!== true &&
isAdmin!== false) {
user.crazy = true;
}
}
Refactoring is painful
0
20
40
60
80
100
120
Pain of Refactoring
Backend
Frontend
X-browser testing doesn’t
scale
• iOS
• Android
• IE Mobile
• Blackberry
• Firefox mobile
• ...
Efficient debugging
• We spend lots of time debugging frontend
code.
• Helpful to know which parts of an application
is well tested => less likely to have bugs.
Additional benefits of
testing
• Find bugs early
• Develop & refactor with confidence
• Tests serve as additional API documentation
• Helps you detect tightly coupled code
Code handover
• Test cases can be immensely useful when
handing over responsibility for a JS module
• Developer Bob quits his job. New guy gets
responsibility of his JS code.
• How will the new guy know what parts of the
codebase safe to change & refactor?
New guy studies codebase
/* I am not sure if we need this, but too scared to delete. */
// drunk, fix later
// TODO make this work
/**
* When I wrote this, only God and I understood what I was doing
* Now, God only knows
**/
scripts/core/application.js
Code handover
New guy, scared
Code handover
• Without test suite, new guy will be afraid to
make any major changes.
• Only minor cosmetic changes on the surface.
• System accumulates cruft over time.
• Sounds familiar?
So, how do I start..?
• Code and design for testability
• Choose the tools to help you
• Automation / CI / Coverage
Writing testable JS
• Keep your JavaScript in JS files
• Never put JavaScript in your HTML
page/tags
• Keep code organized in logical manageable
files. Decide on some max nbr of lines/file.
Writing testable JS
Writing testable JS
• Fat model, skinny view
• Don’t pollute your views with business logic
• Testing pure JS is a lot easier than testing
DOM-dependent JS
• Promotes reuse of your code
Writing testable JS
Ext.define('UserForm', {
extend: 'Ext.FormPanel',
width: 400,
height: 400,
model: new UserModel(),
// Returns true if User is valid
isValid: function (userModel) {
return userModel.name.length > 4 &&
userModel.password.length > 8;
}
});
Mixing view and business logic
Writing testable JS
Ext.define('UserModel', {
extend: 'Ext.data.Model',
name : “”,
password : “”,
// Returns array of User model objects
isValid : function () {
return this.name.length > 4 &&
this.password.length > 8;
}
});
Better:
Writing testable JS
Ext.define('UserForm', {
extend: 'Ext.FormPanel',
width: 400,
height: 400,
model: new UserModel(),
// Returns true if User is valid
isValid: function (userModel) {
return userModel.isValid();
}
});
No business logic in view
Avoid private code
• Avoid overuse of private functions in
closures
• If your code cannot be accessed it cannot
be tested
Tools
Choose your tools
• Last few years has brought numerous new
testing tools to the JavaScript world
• Quite hard to know which to choose,
evaluation needed
• Positive trend, lots of buzz around web testing
Unit Test Tools
• Jasmine
• Siesta
• Buster.js (beta) / Sinon.js
• DOH (Dojo Object Harness)
• Qunit (jQuery)
• JsUnit (abandoned?)
• YUI Test
• Google js-test
• Zombie (headless/Node)
Pure JS Test Tools
• More or less similar approach in most tools
• Define HTML/JS harness, and test suites is
composed by single JS test files.
• Some support/require setup/tearDown
• Others rely on iframes, slower though no
cleanup required
Jasmine
• Simple DOM-less testing
• BDD syntax
• Borrows “the best parts” of ScrewUnit,
JSSpec, JSpec, and RSpec.
Anatomy of a Jasmine test
describe('panda', function () {
it('is happy', function () {
expect(panda).toBe('happy');
});
});
Suite / Spec
Source
panda = 'happy'; // => PASS
Jasmine matchers
Siesta
• Unit testing and functional DOM testing
• Simple TDD syntax
• Test any JS: Ext JS, jQuery, NodeJS etc.
• Automate using PhantomJS & Selenium.
• Extensible, easy to add own assertion
methods
Anatomy of a Siesta test
StartTest(function(t) {
t.diag('Testing jQuery...');
$('body').html('JQuery was here');
t.contentLike(document.body,
'JQuery was here',
'Found correct text in DOM');
});
test-jquery_01.js
Testing Ajax
Testing Ajax
• Try to avoid calling your actual server.
• Use either static JS files with mock data
(async, slower)
• Or Mock the entire Ajax call (sync, faster)
Sinon.js, Jasmine-ajax etc.
Testing Ajax w/ Jasmine
it("should make an AJAX request to the correct URL", function() {
spyOn($, "ajax");
getProduct(123);
expect($.ajax.mostRecentCall.args[0]["url"]).toEqual("/products/123");
});
function getProduct(id) {
$.ajax({
type: "GET",
url: "/products/" + id,
dataType: "json"
});
}
Functional testing
• Test larger piece of your app, or the
application as a whole.
• Simulate user interaction, click, type etc.
• Navigate between pages
Functional testing tools
• Selenium
• Funcunit
• JsTestDriver
• Siesta
• Watir
• DOH Robot (Dojo)
• Sahi
• Squish (Frog Logic)
Interacting with the DOM
Two main approaches of faking a user
• Synthetic events
• Native events (via Java Applet)
Synthetic events
+ Supported in all major browsers
+ Compatible with mobile
+ Don’t rely on native event queue
Tests can be run in parallell.
- Browsers don’t ”trust” synthetic events
- Enter key on a focused link
- Tab between input fields, etc...
- X-browser differences
DOM Events, Key events, key codes (http://unixpapa.com)
Native events
+ Java applets are supported in all desktop
browsers
+ As close to a ’real’ user as possible
- Won’t work on iOS, Android.
- No parallell tests since native event queue
is used.
”Browser Drivers”
Opens real browser instances and ’drives’
them
Outputs commands and evaluates result
Can be quite slow
”Browser Drivers”
Selenium
The most widely used functional testing tool. Firefox Recorder.
JsTestDriver
By Google. ”Remote JavaScript Console”. IntelliJ and Eclipse
Watir
Web Application Testing in Ruby. Also a .NET port, WatiN.
Sahi
By TytoSoftware. Has X-browser recorder.
Headless browsers
• “A web browser without a graphical user
interface”
• Command line interface
• Great for automating tests, integrating with
CI tools (Jenkins, Cruise Control…)
Headless browsers
+ Run tests on command line
+ Faster
+ Automation
+ Doesn’t require an actual browser
- Not 100% accurate, but close.
Headless browsers
PhantomJS (headless WebKit + JavaScript API)
env.js(Runs on Rhino)
JsDom (CommonJS implementation of the DOM)
Phantom JS
Created by Ariya Hidayat (Sencha Inc.)
Fast headless testing
Site scraping
SVG rendering
Supports CoffeeScript
JS Code Coverage
• JsCoverage
Seems abandoned
• ScriptCover
Google Chrome Plugin
• JsTestDriver
Add-in module for coverage
• JesCov
Rhino, Jasmine
Continuous Integration
• Once you have decided on your testing
toolset, integrate it into your CI.
• Automatically run test suite on pre-commit
or post-commit
• Nightly build, full test suite execution,
reporting via email, or other CI systems.
CI Tools
• Jenkins
• Cruise Control
• Test Swarm
So which tools are
right for me?
Evaluating tools
• Some are geared towards specific server side
languages, Java/Ruby/C#
• Prototype and find what works best for you
• Make sure the tool you use integrates nicely
with your IDE and CI-environment
Resources
http://www.adequatelygood.com/2010/7/Writing-Testable-JavaScript
http://blog.jcoglan.com/2011/07/14/refactoring-towards-testable-javascript-part-1/
Resources - Yahoo
http://screen.yahoo.com/
Resources - GTAC
Finally: wise words
”Without unit tests, you’re not
refactoring. You’re just changing
shit.”
Hamlet D’Arcy
That’s all folks!
Questions?
2012 Mats Bryntse
@bryntum

More Related Content

What's hot (20)

Efficient JavaScript Unit Testing, May 2012
Efficient JavaScript Unit Testing, May 2012Efficient JavaScript Unit Testing, May 2012
Efficient JavaScript Unit Testing, May 2012
Hazem Saleh
 
Front-End Testing: Demystified
Front-End Testing: DemystifiedFront-End Testing: Demystified
Front-End Testing: Demystified
Seth McLaughlin
 
Testing Web Applications
Testing Web ApplicationsTesting Web Applications
Testing Web Applications
Seth McLaughlin
 
Browser Automated Testing Frameworks - Nightwatch.js
Browser Automated Testing Frameworks - Nightwatch.jsBrowser Automated Testing Frameworks - Nightwatch.js
Browser Automated Testing Frameworks - Nightwatch.js
Luís Bastião Silva
 
Protractor Tutorial Quality in Agile 2015
Protractor Tutorial Quality in Agile 2015Protractor Tutorial Quality in Agile 2015
Protractor Tutorial Quality in Agile 2015
Andrew Eisenberg
 
Carmen Popoviciu - Protractor styleguide | Codemotion Milan 2015
Carmen Popoviciu - Protractor styleguide | Codemotion Milan 2015Carmen Popoviciu - Protractor styleguide | Codemotion Milan 2015
Carmen Popoviciu - Protractor styleguide | Codemotion Milan 2015
Codemotion
 
Angular UI Testing with Protractor
Angular UI Testing with ProtractorAngular UI Testing with Protractor
Angular UI Testing with Protractor
Andrew Eisenberg
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
Ran Mizrahi
 
Testing ASP.NET - Progressive.NET
Testing ASP.NET - Progressive.NETTesting ASP.NET - Progressive.NET
Testing ASP.NET - Progressive.NET
Ben Hall
 
Jest: Frontend Testing leicht gemacht @EnterJS2018
Jest: Frontend Testing leicht gemacht @EnterJS2018Jest: Frontend Testing leicht gemacht @EnterJS2018
Jest: Frontend Testing leicht gemacht @EnterJS2018
Holger Grosse-Plankermann
 
Test your Javascript! v1.1
Test your Javascript! v1.1Test your Javascript! v1.1
Test your Javascript! v1.1
Eric Wendelin
 
Nightwatch at Tilt
Nightwatch at TiltNightwatch at Tilt
Nightwatch at Tilt
Dave King
 
An Introduction to AngularJS End to End Testing using Protractor
An Introduction to AngularJS End to End Testing using ProtractorAn Introduction to AngularJS End to End Testing using Protractor
An Introduction to AngularJS End to End Testing using Protractor
Cubet Techno Labs
 
Automation Abstraction Layers: Page Objects and Beyond
Automation Abstraction Layers: Page Objects and BeyondAutomation Abstraction Layers: Page Objects and Beyond
Automation Abstraction Layers: Page Objects and Beyond
Alan Richardson
 
Development of automated tests for ext js based web sites
Development of automated tests for ext js based web sitesDevelopment of automated tests for ext js based web sites
Development of automated tests for ext js based web sites
ISsoft
 
Protractor framework – how to make stable e2e tests for Angular applications
Protractor framework – how to make stable e2e tests for Angular applicationsProtractor framework – how to make stable e2e tests for Angular applications
Protractor framework – how to make stable e2e tests for Angular applications
Ludmila Nesvitiy
 
Introduction to Protractor
Introduction to ProtractorIntroduction to Protractor
Introduction to Protractor
Jie-Wei Wu
 
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
Gavin Pickin
 
Test-Driven JavaScript Development (JavaZone 2010)
Test-Driven JavaScript Development (JavaZone 2010)Test-Driven JavaScript Development (JavaZone 2010)
Test-Driven JavaScript Development (JavaZone 2010)
Christian Johansen
 
Automated Web Testing using JavaScript
Automated Web Testing using JavaScriptAutomated Web Testing using JavaScript
Automated Web Testing using JavaScript
Simon Guest
 
Efficient JavaScript Unit Testing, May 2012
Efficient JavaScript Unit Testing, May 2012Efficient JavaScript Unit Testing, May 2012
Efficient JavaScript Unit Testing, May 2012
Hazem Saleh
 
Front-End Testing: Demystified
Front-End Testing: DemystifiedFront-End Testing: Demystified
Front-End Testing: Demystified
Seth McLaughlin
 
Testing Web Applications
Testing Web ApplicationsTesting Web Applications
Testing Web Applications
Seth McLaughlin
 
Browser Automated Testing Frameworks - Nightwatch.js
Browser Automated Testing Frameworks - Nightwatch.jsBrowser Automated Testing Frameworks - Nightwatch.js
Browser Automated Testing Frameworks - Nightwatch.js
Luís Bastião Silva
 
Protractor Tutorial Quality in Agile 2015
Protractor Tutorial Quality in Agile 2015Protractor Tutorial Quality in Agile 2015
Protractor Tutorial Quality in Agile 2015
Andrew Eisenberg
 
Carmen Popoviciu - Protractor styleguide | Codemotion Milan 2015
Carmen Popoviciu - Protractor styleguide | Codemotion Milan 2015Carmen Popoviciu - Protractor styleguide | Codemotion Milan 2015
Carmen Popoviciu - Protractor styleguide | Codemotion Milan 2015
Codemotion
 
Angular UI Testing with Protractor
Angular UI Testing with ProtractorAngular UI Testing with Protractor
Angular UI Testing with Protractor
Andrew Eisenberg
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
Ran Mizrahi
 
Testing ASP.NET - Progressive.NET
Testing ASP.NET - Progressive.NETTesting ASP.NET - Progressive.NET
Testing ASP.NET - Progressive.NET
Ben Hall
 
Jest: Frontend Testing leicht gemacht @EnterJS2018
Jest: Frontend Testing leicht gemacht @EnterJS2018Jest: Frontend Testing leicht gemacht @EnterJS2018
Jest: Frontend Testing leicht gemacht @EnterJS2018
Holger Grosse-Plankermann
 
Test your Javascript! v1.1
Test your Javascript! v1.1Test your Javascript! v1.1
Test your Javascript! v1.1
Eric Wendelin
 
Nightwatch at Tilt
Nightwatch at TiltNightwatch at Tilt
Nightwatch at Tilt
Dave King
 
An Introduction to AngularJS End to End Testing using Protractor
An Introduction to AngularJS End to End Testing using ProtractorAn Introduction to AngularJS End to End Testing using Protractor
An Introduction to AngularJS End to End Testing using Protractor
Cubet Techno Labs
 
Automation Abstraction Layers: Page Objects and Beyond
Automation Abstraction Layers: Page Objects and BeyondAutomation Abstraction Layers: Page Objects and Beyond
Automation Abstraction Layers: Page Objects and Beyond
Alan Richardson
 
Development of automated tests for ext js based web sites
Development of automated tests for ext js based web sitesDevelopment of automated tests for ext js based web sites
Development of automated tests for ext js based web sites
ISsoft
 
Protractor framework – how to make stable e2e tests for Angular applications
Protractor framework – how to make stable e2e tests for Angular applicationsProtractor framework – how to make stable e2e tests for Angular applications
Protractor framework – how to make stable e2e tests for Angular applications
Ludmila Nesvitiy
 
Introduction to Protractor
Introduction to ProtractorIntroduction to Protractor
Introduction to Protractor
Jie-Wei Wu
 
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
Gavin Pickin
 
Test-Driven JavaScript Development (JavaZone 2010)
Test-Driven JavaScript Development (JavaZone 2010)Test-Driven JavaScript Development (JavaZone 2010)
Test-Driven JavaScript Development (JavaZone 2010)
Christian Johansen
 
Automated Web Testing using JavaScript
Automated Web Testing using JavaScriptAutomated Web Testing using JavaScript
Automated Web Testing using JavaScript
Simon Guest
 

Similar to Java script unit testing (20)

Node.js Development Workflow Automation with Grunt.js
Node.js Development Workflow Automation with Grunt.jsNode.js Development Workflow Automation with Grunt.js
Node.js Development Workflow Automation with Grunt.js
kiyanwang
 
TDD super mondays-june-2014
TDD super mondays-june-2014TDD super mondays-june-2014
TDD super mondays-june-2014
Alex Kavanagh
 
Pragmatic Parallels: Java and JavaScript
Pragmatic Parallels: Java and JavaScriptPragmatic Parallels: Java and JavaScript
Pragmatic Parallels: Java and JavaScript
davejohnson
 
Jest: Frontend Testing richtig gemacht @WebworkerNRW
Jest: Frontend Testing richtig gemacht @WebworkerNRWJest: Frontend Testing richtig gemacht @WebworkerNRW
Jest: Frontend Testing richtig gemacht @WebworkerNRW
Holger Grosse-Plankermann
 
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
Ortus Solutions, Corp
 
Quick start with AngularJS
Quick start with AngularJSQuick start with AngularJS
Quick start with AngularJS
Iuliia Baranova
 
Enterprise Strength Mobile JavaScript
Enterprise Strength Mobile JavaScriptEnterprise Strength Mobile JavaScript
Enterprise Strength Mobile JavaScript
Troy Miles
 
Testing mit Codeception: Full-stack testing PHP framework
Testing mit Codeception: Full-stack testing PHP frameworkTesting mit Codeception: Full-stack testing PHP framework
Testing mit Codeception: Full-stack testing PHP framework
SusannSgorzaly
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
Fabio Franzini
 
Testacular
TestacularTestacular
Testacular
James Ford
 
UI Testing Automation
UI Testing AutomationUI Testing Automation
UI Testing Automation
AgileEngine
 
Automated acceptance test
Automated acceptance testAutomated acceptance test
Automated acceptance test
Bryan Liu
 
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 API
Gavin Pickin
 
CBDW2014 - MockBox, get ready to mock your socks off!
CBDW2014 - MockBox, get ready to mock your socks off!CBDW2014 - MockBox, get ready to mock your socks off!
CBDW2014 - MockBox, get ready to mock your socks off!
Ortus Solutions, Corp
 
Top100summit 谷歌-scott-improve your automated web application testing
Top100summit  谷歌-scott-improve your automated web application testingTop100summit  谷歌-scott-improve your automated web application testing
Top100summit 谷歌-scott-improve your automated web application testing
drewz lin
 
Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)
Ran Mizrahi
 
Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)
Ran Mizrahi
 
Mastering Test Automation: How To Use Selenium Successfully
Mastering Test Automation: How To Use Selenium SuccessfullyMastering Test Automation: How To Use Selenium Successfully
Mastering Test Automation: How To Use Selenium Successfully
SpringPeople
 
Agile JavaScript Testing
Agile JavaScript TestingAgile JavaScript Testing
Agile JavaScript Testing
Scott Becker
 
Node.js Development Workflow Automation with Grunt.js
Node.js Development Workflow Automation with Grunt.jsNode.js Development Workflow Automation with Grunt.js
Node.js Development Workflow Automation with Grunt.js
kiyanwang
 
TDD super mondays-june-2014
TDD super mondays-june-2014TDD super mondays-june-2014
TDD super mondays-june-2014
Alex Kavanagh
 
Pragmatic Parallels: Java and JavaScript
Pragmatic Parallels: Java and JavaScriptPragmatic Parallels: Java and JavaScript
Pragmatic Parallels: Java and JavaScript
davejohnson
 
Jest: Frontend Testing richtig gemacht @WebworkerNRW
Jest: Frontend Testing richtig gemacht @WebworkerNRWJest: Frontend Testing richtig gemacht @WebworkerNRW
Jest: Frontend Testing richtig gemacht @WebworkerNRW
Holger Grosse-Plankermann
 
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
Ortus Solutions, Corp
 
Quick start with AngularJS
Quick start with AngularJSQuick start with AngularJS
Quick start with AngularJS
Iuliia Baranova
 
Enterprise Strength Mobile JavaScript
Enterprise Strength Mobile JavaScriptEnterprise Strength Mobile JavaScript
Enterprise Strength Mobile JavaScript
Troy Miles
 
Testing mit Codeception: Full-stack testing PHP framework
Testing mit Codeception: Full-stack testing PHP frameworkTesting mit Codeception: Full-stack testing PHP framework
Testing mit Codeception: Full-stack testing PHP framework
SusannSgorzaly
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
Fabio Franzini
 
UI Testing Automation
UI Testing AutomationUI Testing Automation
UI Testing Automation
AgileEngine
 
Automated acceptance test
Automated acceptance testAutomated acceptance test
Automated acceptance test
Bryan Liu
 
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 API
Gavin Pickin
 
CBDW2014 - MockBox, get ready to mock your socks off!
CBDW2014 - MockBox, get ready to mock your socks off!CBDW2014 - MockBox, get ready to mock your socks off!
CBDW2014 - MockBox, get ready to mock your socks off!
Ortus Solutions, Corp
 
Top100summit 谷歌-scott-improve your automated web application testing
Top100summit  谷歌-scott-improve your automated web application testingTop100summit  谷歌-scott-improve your automated web application testing
Top100summit 谷歌-scott-improve your automated web application testing
drewz lin
 
Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)
Ran Mizrahi
 
Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)
Ran Mizrahi
 
Mastering Test Automation: How To Use Selenium Successfully
Mastering Test Automation: How To Use Selenium SuccessfullyMastering Test Automation: How To Use Selenium Successfully
Mastering Test Automation: How To Use Selenium Successfully
SpringPeople
 
Agile JavaScript Testing
Agile JavaScript TestingAgile JavaScript Testing
Agile JavaScript Testing
Scott Becker
 
Ad

Recently uploaded (20)

Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
Edge AI and Vision Alliance
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too LateKubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and ImplementationAI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
Christine Shepherd
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven InfrastructureNo-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und AnwendungsfälleDomino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
panagenda
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
Secure Access with Azure Active Directory
Secure Access with Azure Active DirectorySecure Access with Azure Active Directory
Secure Access with Azure Active Directory
VICTOR MAESTRE RAMIREZ
 
Edge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdfEdge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdf
AmirStern2
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
Ben Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding WorldBen Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding World
AWS Chicago
 
Crypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdfCrypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdf
Stephen Perrenod
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Infrassist Technologies Pvt. Ltd.
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
PyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent IntegrationPyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent Integration
barqawicloud
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
Edge AI and Vision Alliance
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too LateKubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and ImplementationAI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
Christine Shepherd
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven InfrastructureNo-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und AnwendungsfälleDomino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
panagenda
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
Secure Access with Azure Active Directory
Secure Access with Azure Active DirectorySecure Access with Azure Active Directory
Secure Access with Azure Active Directory
VICTOR MAESTRE RAMIREZ
 
Edge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdfEdge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdf
AmirStern2
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
Ben Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding WorldBen Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding World
AWS Chicago
 
Crypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdfCrypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdf
Stephen Perrenod
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Infrassist Technologies Pvt. Ltd.
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
PyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent IntegrationPyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent Integration
barqawicloud
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Ad

Java script unit testing

  • 1. JavaScript Unit Testing 2012 Mats Bryntse @bryntum
  • 2. var me = { name : ”Mats Bryntse”, age : 35, from : ”Helsingborg, Sweden”, does : ”Runs Bryntum”, site : ” www.bryntum.com”, twitter : ”@bryntum”, likes : ”Ext JS” }; About me
  • 3. What we do JavaScript scheduling and Gantt charts Siesta (JS Test Tool)
  • 5. First, a quick survey: How many of you...
  • 6. • have a web application a frontend test suite? • have frontend test suite as part of your CI proc. • run your test suite in all major browsers? • have zero or less frontend tests for your app. How many of you...
  • 7. Unit test JS, really?? But... ”... my code is bug free” ”...testing takes time away from adding new features (+ new bugs)” ”...it’s QA’s job to test” ”... it’s boring and I’ll quit my job”
  • 9. A typical web app... Interwebs http://www.app.com
  • 10. The backend • Single controlled platform • Simple to test and refactor • Good IDEs and tools C# Java PHP
  • 11. The frontend • Multiple platforms & versions (Mac, Windows XP/Vista/7, Linux...) • Multiple browser versions • Hard to refactor • JavaScript support in IDEs is still !== awesome
  • 12. Conclusion • Developing frontend code is harder than developing server code. • Mainly due to lack of good tools • Lots of uncertainty, x-browser issues • IE6
  • 13. As good JS dev tools are hard to find, we need to make good use of existing tools and practices.
  • 15. Easy to introduce unforeseen errors isUserCrazy: function(user, isAdmin) { // DON’T CHANGE THIS if (user.age > 35 && isAdmin!== true && isAdmin!== false) { user.crazy = true; } }
  • 16. Refactoring is painful 0 20 40 60 80 100 120 Pain of Refactoring Backend Frontend
  • 17. X-browser testing doesn’t scale • iOS • Android • IE Mobile • Blackberry • Firefox mobile • ...
  • 18. Efficient debugging • We spend lots of time debugging frontend code. • Helpful to know which parts of an application is well tested => less likely to have bugs.
  • 19. Additional benefits of testing • Find bugs early • Develop & refactor with confidence • Tests serve as additional API documentation • Helps you detect tightly coupled code
  • 20. Code handover • Test cases can be immensely useful when handing over responsibility for a JS module • Developer Bob quits his job. New guy gets responsibility of his JS code. • How will the new guy know what parts of the codebase safe to change & refactor?
  • 21. New guy studies codebase /* I am not sure if we need this, but too scared to delete. */ // drunk, fix later // TODO make this work /** * When I wrote this, only God and I understood what I was doing * Now, God only knows **/ scripts/core/application.js
  • 23. Code handover • Without test suite, new guy will be afraid to make any major changes. • Only minor cosmetic changes on the surface. • System accumulates cruft over time. • Sounds familiar?
  • 24. So, how do I start..? • Code and design for testability • Choose the tools to help you • Automation / CI / Coverage
  • 25. Writing testable JS • Keep your JavaScript in JS files • Never put JavaScript in your HTML page/tags • Keep code organized in logical manageable files. Decide on some max nbr of lines/file.
  • 27. Writing testable JS • Fat model, skinny view • Don’t pollute your views with business logic • Testing pure JS is a lot easier than testing DOM-dependent JS • Promotes reuse of your code
  • 28. Writing testable JS Ext.define('UserForm', { extend: 'Ext.FormPanel', width: 400, height: 400, model: new UserModel(), // Returns true if User is valid isValid: function (userModel) { return userModel.name.length > 4 && userModel.password.length > 8; } }); Mixing view and business logic
  • 29. Writing testable JS Ext.define('UserModel', { extend: 'Ext.data.Model', name : “”, password : “”, // Returns array of User model objects isValid : function () { return this.name.length > 4 && this.password.length > 8; } }); Better:
  • 30. Writing testable JS Ext.define('UserForm', { extend: 'Ext.FormPanel', width: 400, height: 400, model: new UserModel(), // Returns true if User is valid isValid: function (userModel) { return userModel.isValid(); } }); No business logic in view
  • 31. Avoid private code • Avoid overuse of private functions in closures • If your code cannot be accessed it cannot be tested
  • 32. Tools
  • 33. Choose your tools • Last few years has brought numerous new testing tools to the JavaScript world • Quite hard to know which to choose, evaluation needed • Positive trend, lots of buzz around web testing
  • 34. Unit Test Tools • Jasmine • Siesta • Buster.js (beta) / Sinon.js • DOH (Dojo Object Harness) • Qunit (jQuery) • JsUnit (abandoned?) • YUI Test • Google js-test • Zombie (headless/Node)
  • 35. Pure JS Test Tools • More or less similar approach in most tools • Define HTML/JS harness, and test suites is composed by single JS test files. • Some support/require setup/tearDown • Others rely on iframes, slower though no cleanup required
  • 36. Jasmine • Simple DOM-less testing • BDD syntax • Borrows “the best parts” of ScrewUnit, JSSpec, JSpec, and RSpec.
  • 37. Anatomy of a Jasmine test describe('panda', function () { it('is happy', function () { expect(panda).toBe('happy'); }); }); Suite / Spec Source panda = 'happy'; // => PASS
  • 39. Siesta • Unit testing and functional DOM testing • Simple TDD syntax • Test any JS: Ext JS, jQuery, NodeJS etc. • Automate using PhantomJS & Selenium. • Extensible, easy to add own assertion methods
  • 40. Anatomy of a Siesta test StartTest(function(t) { t.diag('Testing jQuery...'); $('body').html('JQuery was here'); t.contentLike(document.body, 'JQuery was here', 'Found correct text in DOM'); }); test-jquery_01.js
  • 42. Testing Ajax • Try to avoid calling your actual server. • Use either static JS files with mock data (async, slower) • Or Mock the entire Ajax call (sync, faster) Sinon.js, Jasmine-ajax etc.
  • 43. Testing Ajax w/ Jasmine it("should make an AJAX request to the correct URL", function() { spyOn($, "ajax"); getProduct(123); expect($.ajax.mostRecentCall.args[0]["url"]).toEqual("/products/123"); }); function getProduct(id) { $.ajax({ type: "GET", url: "/products/" + id, dataType: "json" }); }
  • 44. Functional testing • Test larger piece of your app, or the application as a whole. • Simulate user interaction, click, type etc. • Navigate between pages
  • 45. Functional testing tools • Selenium • Funcunit • JsTestDriver • Siesta • Watir • DOH Robot (Dojo) • Sahi • Squish (Frog Logic)
  • 46. Interacting with the DOM Two main approaches of faking a user • Synthetic events • Native events (via Java Applet)
  • 47. Synthetic events + Supported in all major browsers + Compatible with mobile + Don’t rely on native event queue Tests can be run in parallell. - Browsers don’t ”trust” synthetic events - Enter key on a focused link - Tab between input fields, etc... - X-browser differences DOM Events, Key events, key codes (http://unixpapa.com)
  • 48. Native events + Java applets are supported in all desktop browsers + As close to a ’real’ user as possible - Won’t work on iOS, Android. - No parallell tests since native event queue is used.
  • 49. ”Browser Drivers” Opens real browser instances and ’drives’ them Outputs commands and evaluates result Can be quite slow
  • 50. ”Browser Drivers” Selenium The most widely used functional testing tool. Firefox Recorder. JsTestDriver By Google. ”Remote JavaScript Console”. IntelliJ and Eclipse Watir Web Application Testing in Ruby. Also a .NET port, WatiN. Sahi By TytoSoftware. Has X-browser recorder.
  • 51. Headless browsers • “A web browser without a graphical user interface” • Command line interface • Great for automating tests, integrating with CI tools (Jenkins, Cruise Control…)
  • 52. Headless browsers + Run tests on command line + Faster + Automation + Doesn’t require an actual browser - Not 100% accurate, but close.
  • 53. Headless browsers PhantomJS (headless WebKit + JavaScript API) env.js(Runs on Rhino) JsDom (CommonJS implementation of the DOM)
  • 54. Phantom JS Created by Ariya Hidayat (Sencha Inc.) Fast headless testing Site scraping SVG rendering Supports CoffeeScript
  • 55. JS Code Coverage • JsCoverage Seems abandoned • ScriptCover Google Chrome Plugin • JsTestDriver Add-in module for coverage • JesCov Rhino, Jasmine
  • 56. Continuous Integration • Once you have decided on your testing toolset, integrate it into your CI. • Automatically run test suite on pre-commit or post-commit • Nightly build, full test suite execution, reporting via email, or other CI systems.
  • 57. CI Tools • Jenkins • Cruise Control • Test Swarm
  • 58. So which tools are right for me?
  • 59. Evaluating tools • Some are geared towards specific server side languages, Java/Ruby/C# • Prototype and find what works best for you • Make sure the tool you use integrates nicely with your IDE and CI-environment
  • 63. Finally: wise words ”Without unit tests, you’re not refactoring. You’re just changing shit.” Hamlet D’Arcy
  • 64. That’s all folks! Questions? 2012 Mats Bryntse @bryntum