SlideShare a Scribd company logo
Writing and Testing JavaScript-heavy Web 2.0 apps with JSUnit Authors: Alex Chaffee, Pivotal Labs Edward Hieatt, Pivotal Labs
Abstract With the advent of the so-called Web 2.0 platform, more and more applications are using client-side JavaScript for vital features. In fact, some applications are so JS-heavy that they redefine JavaScript as a full-fledged application development language.  In this tutorial we discuss some architectural considerations of JS- and AJAX-heavy applications and present in detail our testing framework, with plenty of code examples and live demos.
JS Application Architectures Traditional: Minimal JS JS for validation JS for user responsiveness JS for DHTML JS for layout tweaks (where CSS falls down)
JS Application Architectures (cont.) AJAX Architecture Widgets and functions live on client Use XMLHttpRequest for immediate or background requests to server Use JSON or XML for data transport
JS Application Architectures (cont.) Dynamic Architecture:  server-generated JS RJS Google Web Toolkit Big advantage:  unified codebase -> DRY Disadvantages: Latency Harder to test
Application Architectures (cont.) Client-Server JS MVC: Heavy JS In this architecture, the JavaScript code takes the form of a full-fledged application. Using JSON to transfer data back and forth between the server-side API, the JavaScript application maintains its own domain objects and executes its own business rules. Can violate DRY
Application Architectures (cont.) Hybrid Naturally, you can mix and match the above techniques Complicates your coding and testing Can violate DRY
Testing Strategies Unit Testing: JSUnit Integration Testing: Selenium WATIR
JavaScript Essence Dynamic Interpreted Prototype-based OO Object = Hash Everything (even Function) is a Hash Sort of a mutant hybrid of Java and Ruby
JavaScript Cons Functions have loose binding “ this” isn't always correct Workaround: Use  bind  (part of prototype.js) Frustrating syntax and semantics Symbols are globally scoped by default You must remember “this” Too easy to make global variables null vs. undefined vs. 0 All members are public No OO inheritance Several hacks to simulate inheritance Rely more on composition Browser differences (esp. DOM API) and bugs No “include” or “require” We rolled our own Painful debugging Unreliable stack traces Two different GCs Memory leaks via DOM Third-party libraries rarely tested
JavaScript Tools and Libraries
Firefox Extensions Web Developer Firebug ROCKS
Development Environments IDEA Eclipse TextMate ?
prototype.js Library bind $ $H, $A, each, etc. extend Ajax.Request Element.hide Other useful stuff
JS UI libraries script.aculo.us Very Good Popular (easy to find help) Yahoo UI Excellent Drag and drop, animation, calendar, etc.
Asset Packager Combines multiple JS files into one Also CSS Reduces Latency Also Steve Conover’s inline merger looks promising
JSUnit “ Controlling The Insanity” Unit Testing is essential for all but the most trivial JavaScript
Pivotal Assertions
clock.js Testing utility class we wrote Overrides setTimeout Allows unit testing of time-based operations without sleeping
ajax.js AjaxUnit Overrides Prototype AJAX classes Stubs out the network interface Allows unit testing of AJAX calls
Mock Objects in JS We don’t know of any real mocking framework for JS We use stubs, spies, object mothers and mock methods
Client-Server Communication
Client-Server Communication: Let me count the ways HTTP Including GET, POST, cookies, etc. CGI AJAX+XML AJAX+JSON AJAX+HTML AJAX+JS RJS
AJAX “ Asynchronous JavaScript And XML” Client calls server with CGI GET or POST via XMLHttpRequest API Server responds Client does something without redrawing entire page
AJAX+XML Response contains XML Original implementation of AJAX Not used much now (?) I've heard of doing XSL but that's mostly on IE-only apps
JSON Evaluates to JS values (hashes and arrays) Example: {   "Image": {   "Width":  800,   "Height": 600,   "Title":  "View from 15th Floor",   "Thumbnail": {   "Url": "http: //scd.mmb1.com/image/481989943",   "Height": 125,   "Width":  "100"   },   "IDs": [116, 943, 234, 38793]   } }
AJAX+JSON (AJAJ?) Proper client-server communication Client sends requests in CGI, gets responses as pure data Client evaluates data, actively performs response Interacts with DOM Creates/removes/modifies/copies HTML elements
AJAX+HTML Server executes RHTML/JSP/etc. AJAX response contains HTML Client splats it onto the page
AJAX+JS AJAX response contains JavaScript code Client calls  eval()  on it Powerful and a little scary Hard to test
RJS Part of Ruby on Rails Generates JS via Ruby methods Not as scary as raw JS since it’s coming from a tested library
Latency: The AJAX killer This AJAX stuff really is client-server communication If the server is slow, your app crawls to a halt -- and  inside  a page, not just between pages Less user feedback for a hung AJAX call Can lead to multiple clicks, reloads, confusion, etc.
Solving Latency The Easy Way:  Use a spinny icon Still requires UI/UE design
Solving Latency The Hard Way: To solve, you must write a lot of code on the client to react immediately to user actions, then queue up requests and deal gracefully once the server reponds Error handling Command queue Undo Dynamic/incremental data updates This leads naturally to true MVC in JS
JS MVC Architecture JSON Model Objects Notify View Components Render DOM User Events Enqueue Command Objects Execute / undo AJAX (CGI)
Integration Testing with Selenium Selenium… Runs in the browser Executes your app in a frame Simulates user actions via JavaScript Goes all the way to the server and back Complementary to JSUnit JSUnit tests JS pages and libraries only, not interaction with server Selenium is fun to watch Integrated into Continuous Integration like JSUnit Catch our talks on Wednesday (Selenium) and Thursday (CI)
Q&A
More Examples
Clock We wrote our JS “Mock Clock” test-first Actually, it’s a stub, not a mock :-) Illustrates a true (isolated) unit test of a utility class
Weaver The Weaver takes two arrays and returns the set of changes required to transform one into the other Used by Tracker’s list widgets Illustrates use of roll-your-own test spies
DateWidget We wrapped Yahoo’s YUI Calendar widget to add a text field with validation and pop-up-on-activate Illustrates Testing with UI events Using a “demo.html” page Wrapping a third-party widget with tests
Server Proxy Illustrates AjaxUnit (ajax.js) mocking out the networking layer
Add Note Command Tests the command which adds a note (comment) to a story Does not test the networking layer, just the command object Demonstrates use of stubs and object mother (JsonFactory)
Login Widget PeerToPatent uses page caching, so we have to render the “you’re logged in / please log in” area of the screen in JavaScript
Cacheable Flash Not that kind of Flash… “Flash” is Rails for “Message Box” In order for dynamic information to be rendered inside of a statically cached page, we put it into a cookie, and render the cookie’s contents with JavaScript
Cookie Library Illustrates testing a third-party library We found bugs in it, esp. IE 7 We had to patch it
JS Paginator Illustrates receiving JSON with data Download (actually render) entire data set on page load, then render some at a time Doesn’t scale to large datasets, like Rico LiveGrid does
Experimentation Since this is an agile conference, if there's time and interest, we can get volunteers from the audience to come up and pair program with the presenters on stage. solving problems posed by the audience.
Where to find more info? http://jsunit.net http://pivotallabs.com
Ad

Recommended

JsUnit
JsUnit
Alex Chaffee
 
Tellurium.A.New.Approach.For.Web.Testing
Tellurium.A.New.Approach.For.Web.Testing
John.Jian.Fang
 
Tellurium At Rich Web Experience2009
Tellurium At Rich Web Experience2009
John.Jian.Fang
 
Automating UI testing
Automating UI testing
Adam Siton
 
Ten Minutes To Tellurium
Ten Minutes To Tellurium
John.Jian.Fang
 
SWTBot Tutorial
SWTBot Tutorial
Chris Aniszczyk
 
Tellurium 0.7.0 presentation
Tellurium 0.7.0 presentation
John.Jian.Fang
 
SwtBot: Unit Testing Made Easy
SwtBot: Unit Testing Made Easy
Ankit Goel
 
Swtbot
Swtbot
cristitep
 
Functional Testing made easy with SWTBot for Developers and Testers
Functional Testing made easy with SWTBot for Developers and Testers
Aurélien Pupier
 
UI Testing Best Practices - An Expected Journey
UI Testing Best Practices - An Expected Journey
Oren Farhi
 
[XCode] Automating UI Testing
[XCode] Automating UI Testing
Phineas Huang
 
Tellurium.A.New.Approach.For.Web.Testing.V5
Tellurium.A.New.Approach.For.Web.Testing.V5
John.Jian.Fang
 
Sencha / ExtJS : Object Oriented JavaScript
Sencha / ExtJS : Object Oriented JavaScript
Rohan Chandane
 
Developing Java SWT Applications - A Starter
Developing Java SWT Applications - A Starter
vcaselli
 
GWT = easy AJAX
GWT = easy AJAX
Olivier Gérardin
 
UI Testing Automation - Alex Kalinovsky - CreamTec LLC
UI Testing Automation - Alex Kalinovsky - CreamTec LLC
Jim Lane
 
ExtJs Basic Part-1
ExtJs Basic Part-1
Mindfire Solutions
 
Automated Xcode 7 UI Testing
Automated Xcode 7 UI Testing
Jouni Miettunen
 
Automation Abstraction Layers: Page Objects and Beyond
Automation Abstraction Layers: Page Objects and Beyond
Alan Richardson
 
iOS UI Testing in Xcode
iOS UI Testing in Xcode
Jz Chang
 
6 swt programming
6 swt programming
Prakash Sweet
 
Hands on Exploration of Page Objects and Abstraction Layers with Selenium Web...
Hands on Exploration of Page Objects and Abstraction Layers with Selenium Web...
Alan Richardson
 
Manageable Robust Automated Ui Test
Manageable Robust Automated Ui Test
John.Jian.Fang
 
XCUITest for iOS App Testing and how to test with Xcode
XCUITest for iOS App Testing and how to test with Xcode
pCloudy
 
Adam Peller Interoperable Ajax Tools And Mashups
Adam Peller Interoperable Ajax Tools And Mashups
Ajax Experience 2009
 
Deep Dive Modern Apps Lifecycle with Visual Studio 2012: How to create cross ...
Deep Dive Modern Apps Lifecycle with Visual Studio 2012: How to create cross ...
Microsoft Developer Network (MSDN) - Belgium and Luxembourg
 
Automating with selenium2
Automating with selenium2
mindqqa
 
Testing writing
Testing writing
Marta Ribas
 
Testing writing (for Language Teachers)
Testing writing (for Language Teachers)
Wenlie Jean
 

More Related Content

What's hot (20)

Swtbot
Swtbot
cristitep
 
Functional Testing made easy with SWTBot for Developers and Testers
Functional Testing made easy with SWTBot for Developers and Testers
Aurélien Pupier
 
UI Testing Best Practices - An Expected Journey
UI Testing Best Practices - An Expected Journey
Oren Farhi
 
[XCode] Automating UI Testing
[XCode] Automating UI Testing
Phineas Huang
 
Tellurium.A.New.Approach.For.Web.Testing.V5
Tellurium.A.New.Approach.For.Web.Testing.V5
John.Jian.Fang
 
Sencha / ExtJS : Object Oriented JavaScript
Sencha / ExtJS : Object Oriented JavaScript
Rohan Chandane
 
Developing Java SWT Applications - A Starter
Developing Java SWT Applications - A Starter
vcaselli
 
GWT = easy AJAX
GWT = easy AJAX
Olivier Gérardin
 
UI Testing Automation - Alex Kalinovsky - CreamTec LLC
UI Testing Automation - Alex Kalinovsky - CreamTec LLC
Jim Lane
 
ExtJs Basic Part-1
ExtJs Basic Part-1
Mindfire Solutions
 
Automated Xcode 7 UI Testing
Automated Xcode 7 UI Testing
Jouni Miettunen
 
Automation Abstraction Layers: Page Objects and Beyond
Automation Abstraction Layers: Page Objects and Beyond
Alan Richardson
 
iOS UI Testing in Xcode
iOS UI Testing in Xcode
Jz Chang
 
6 swt programming
6 swt programming
Prakash Sweet
 
Hands on Exploration of Page Objects and Abstraction Layers with Selenium Web...
Hands on Exploration of Page Objects and Abstraction Layers with Selenium Web...
Alan Richardson
 
Manageable Robust Automated Ui Test
Manageable Robust Automated Ui Test
John.Jian.Fang
 
XCUITest for iOS App Testing and how to test with Xcode
XCUITest for iOS App Testing and how to test with Xcode
pCloudy
 
Adam Peller Interoperable Ajax Tools And Mashups
Adam Peller Interoperable Ajax Tools And Mashups
Ajax Experience 2009
 
Deep Dive Modern Apps Lifecycle with Visual Studio 2012: How to create cross ...
Deep Dive Modern Apps Lifecycle with Visual Studio 2012: How to create cross ...
Microsoft Developer Network (MSDN) - Belgium and Luxembourg
 
Automating with selenium2
Automating with selenium2
mindqqa
 
Functional Testing made easy with SWTBot for Developers and Testers
Functional Testing made easy with SWTBot for Developers and Testers
Aurélien Pupier
 
UI Testing Best Practices - An Expected Journey
UI Testing Best Practices - An Expected Journey
Oren Farhi
 
[XCode] Automating UI Testing
[XCode] Automating UI Testing
Phineas Huang
 
Tellurium.A.New.Approach.For.Web.Testing.V5
Tellurium.A.New.Approach.For.Web.Testing.V5
John.Jian.Fang
 
Sencha / ExtJS : Object Oriented JavaScript
Sencha / ExtJS : Object Oriented JavaScript
Rohan Chandane
 
Developing Java SWT Applications - A Starter
Developing Java SWT Applications - A Starter
vcaselli
 
UI Testing Automation - Alex Kalinovsky - CreamTec LLC
UI Testing Automation - Alex Kalinovsky - CreamTec LLC
Jim Lane
 
Automated Xcode 7 UI Testing
Automated Xcode 7 UI Testing
Jouni Miettunen
 
Automation Abstraction Layers: Page Objects and Beyond
Automation Abstraction Layers: Page Objects and Beyond
Alan Richardson
 
iOS UI Testing in Xcode
iOS UI Testing in Xcode
Jz Chang
 
Hands on Exploration of Page Objects and Abstraction Layers with Selenium Web...
Hands on Exploration of Page Objects and Abstraction Layers with Selenium Web...
Alan Richardson
 
Manageable Robust Automated Ui Test
Manageable Robust Automated Ui Test
John.Jian.Fang
 
XCUITest for iOS App Testing and how to test with Xcode
XCUITest for iOS App Testing and how to test with Xcode
pCloudy
 
Adam Peller Interoperable Ajax Tools And Mashups
Adam Peller Interoperable Ajax Tools And Mashups
Ajax Experience 2009
 
Automating with selenium2
Automating with selenium2
mindqqa
 

Viewers also liked (7)

Testing writing
Testing writing
Marta Ribas
 
Testing writing (for Language Teachers)
Testing writing (for Language Teachers)
Wenlie Jean
 
Writing and testing high frequency trading engines in java
Writing and testing high frequency trading engines in java
Peter Lawrey
 
Testing Writing and Rubrics
Testing Writing and Rubrics
Sarwar Dilshad Ganjo
 
Testing writing
Testing writing
Maury Martinez
 
Testing writing
Testing writing
Jenny Aque
 
Testing writing
Testing writing
Andrea Bacigalupi Troule
 
Testing writing (for Language Teachers)
Testing writing (for Language Teachers)
Wenlie Jean
 
Writing and testing high frequency trading engines in java
Writing and testing high frequency trading engines in java
Peter Lawrey
 
Testing writing
Testing writing
Jenny Aque
 
Ad

Similar to Writing and Testing JavaScript-heavy Web 2.0 apps with JSUnit (20)

Testing Ext JS and Sencha Touch
Testing Ext JS and Sencha Touch
Mats Bryntse
 
Java script unit testing
Java script unit testing
Mats Bryntse
 
Best practices for JavaScript RIAs
Best practices for JavaScript RIAs
Carlos Ble
 
Test-Driven JavaScript Development (JavaZone 2010)
Test-Driven JavaScript Development (JavaZone 2010)
Christian Johansen
 
Reliable Javascript
Reliable Javascript
Glenn Stovall
 
JavaScript Unit Testing
JavaScript Unit Testing
Christian Johansen
 
Test strategy for web development
Test strategy for web development
alice yang
 
Writing testable js [by Ted Piotrowski]
Writing testable js [by Ted Piotrowski]
JavaScript Meetup HCMC
 
Javascript unit testing, yes we can e big
Javascript unit testing, yes we can e big
Andy Peterson
 
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
Anup Singh
 
Pragmatic Parallels: Java and JavaScript
Pragmatic Parallels: Java and JavaScript
davejohnson
 
Js unit testingpresentation
Js unit testingpresentation
Jonathan Gregory
 
Building a JavaScript Library
Building a JavaScript Library
jeresig
 
Building Rich User Experiences Without JavaScript Spaghetti
Building Rich User Experiences Without JavaScript Spaghetti
Jared Faris
 
3 WAYS TO TEST YOUR COLDFUSION API
3 WAYS TO TEST YOUR COLDFUSION API
Gavin Pickin
 
3 WAYS TO TEST YOUR COLDFUSION API -
3 WAYS TO TEST YOUR COLDFUSION API -
Ortus Solutions, Corp
 
JavaScript Libraries (@Media)
JavaScript Libraries (@Media)
jeresig
 
Dot Net Notts Js Unit Testing at Microlise
Dot Net Notts Js Unit Testing at Microlise
Jonathan Gregory
 
JavaScript Libraries (Ajax Exp 2006)
JavaScript Libraries (Ajax Exp 2006)
jeresig
 
Javascript for Wep Apps
Javascript for Wep Apps
Michael Puckett
 
Testing Ext JS and Sencha Touch
Testing Ext JS and Sencha Touch
Mats Bryntse
 
Java script unit testing
Java script unit testing
Mats Bryntse
 
Best practices for JavaScript RIAs
Best practices for JavaScript RIAs
Carlos Ble
 
Test-Driven JavaScript Development (JavaZone 2010)
Test-Driven JavaScript Development (JavaZone 2010)
Christian Johansen
 
Reliable Javascript
Reliable Javascript
Glenn Stovall
 
Test strategy for web development
Test strategy for web development
alice yang
 
Writing testable js [by Ted Piotrowski]
Writing testable js [by Ted Piotrowski]
JavaScript Meetup HCMC
 
Javascript unit testing, yes we can e big
Javascript unit testing, yes we can e big
Andy Peterson
 
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
Anup Singh
 
Pragmatic Parallels: Java and JavaScript
Pragmatic Parallels: Java and JavaScript
davejohnson
 
Js unit testingpresentation
Js unit testingpresentation
Jonathan Gregory
 
Building a JavaScript Library
Building a JavaScript Library
jeresig
 
Building Rich User Experiences Without JavaScript Spaghetti
Building Rich User Experiences Without JavaScript Spaghetti
Jared Faris
 
3 WAYS TO TEST YOUR COLDFUSION API
3 WAYS TO TEST YOUR COLDFUSION API
Gavin Pickin
 
3 WAYS TO TEST YOUR COLDFUSION API -
3 WAYS TO TEST YOUR COLDFUSION API -
Ortus Solutions, Corp
 
JavaScript Libraries (@Media)
JavaScript Libraries (@Media)
jeresig
 
Dot Net Notts Js Unit Testing at Microlise
Dot Net Notts Js Unit Testing at Microlise
Jonathan Gregory
 
JavaScript Libraries (Ajax Exp 2006)
JavaScript Libraries (Ajax Exp 2006)
jeresig
 
Ad

Recently uploaded (20)

cost of capital under invetment for MBAall
cost of capital under invetment for MBAall
NARESH GUDURU
 
IT Companies in Magarpatta: A Thriving Hub of Technology and Innovation
IT Companies in Magarpatta: A Thriving Hub of Technology and Innovation
prernarathi90
 
International Business, 4th Edition- Alan M. Rugman.pdf
International Business, 4th Edition- Alan M. Rugman.pdf
GamingwithUBAID
 
StarOps- AI-native platform that lets you deploy and manage production infras...
StarOps- AI-native platform that lets you deploy and manage production infras...
StarOps
 
IEA_Press_Release_Tullow_Agreement-16-6-2025-1.pdf
IEA_Press_Release_Tullow_Agreement-16-6-2025-1.pdf
businessweekghana
 
Paul Turovsky - A Key Contributor
Paul Turovsky - A Key Contributor
Paul Turovsky
 
Recruitment Policy Sample, Recruitment Policy PDF
Recruitment Policy Sample, Recruitment Policy PDF
SeemaAgrawal43
 
Webinar: Why Odoo is a game-changer for Service Companies
Webinar: Why Odoo is a game-changer for Service Companies
dear digital
 
Power of the Many: Digital Energy Masterclass
Power of the Many: Digital Energy Masterclass
mariana491193
 
Company Profile [Popular Group of Industries]
Company Profile [Popular Group of Industries]
irtizashirazi
 
Ian McAllister - Respected Photographer And Writer
Ian McAllister - Respected Photographer And Writer
Ian McAllister
 
ERP Modernization in 2025: A Practical Guide for CIOs
ERP Modernization in 2025: A Practical Guide for CIOs
Praxis Info Solutions
 
SACRS_Spring Mag 2025 Graceada Article.pdf
SACRS_Spring Mag 2025 Graceada Article.pdf
matthieu81
 
Book - Behavioral finance and wealth management(1).pdf
Book - Behavioral finance and wealth management(1).pdf
GamingwithUBAID
 
Streamline Success: How Well-Defined SOPs Drive Organizational Efficiency
Streamline Success: How Well-Defined SOPs Drive Organizational Efficiency
RUPAL AGARWAL
 
What Drives Collectors in Sports and Beyond, and How Mantel is Bringing Them ...
What Drives Collectors in Sports and Beyond, and How Mantel is Bringing Them ...
Neil Horowitz
 
From Visibility to Action: How Modern Cloud Teams Regain Control
From Visibility to Action: How Modern Cloud Teams Regain Control
Amnic
 
smidmart industrial Automation Ones Stop Solution
smidmart industrial Automation Ones Stop Solution
smidmart
 
The APCO Geopolitical Radar Q3 2025 Edition
The APCO Geopolitical Radar Q3 2025 Edition
APCO
 
Enterprise Architecture Professional Journal Vol IX June 2025.pdf
Enterprise Architecture Professional Journal Vol IX June 2025.pdf
Darryl_Carr
 
cost of capital under invetment for MBAall
cost of capital under invetment for MBAall
NARESH GUDURU
 
IT Companies in Magarpatta: A Thriving Hub of Technology and Innovation
IT Companies in Magarpatta: A Thriving Hub of Technology and Innovation
prernarathi90
 
International Business, 4th Edition- Alan M. Rugman.pdf
International Business, 4th Edition- Alan M. Rugman.pdf
GamingwithUBAID
 
StarOps- AI-native platform that lets you deploy and manage production infras...
StarOps- AI-native platform that lets you deploy and manage production infras...
StarOps
 
IEA_Press_Release_Tullow_Agreement-16-6-2025-1.pdf
IEA_Press_Release_Tullow_Agreement-16-6-2025-1.pdf
businessweekghana
 
Paul Turovsky - A Key Contributor
Paul Turovsky - A Key Contributor
Paul Turovsky
 
Recruitment Policy Sample, Recruitment Policy PDF
Recruitment Policy Sample, Recruitment Policy PDF
SeemaAgrawal43
 
Webinar: Why Odoo is a game-changer for Service Companies
Webinar: Why Odoo is a game-changer for Service Companies
dear digital
 
Power of the Many: Digital Energy Masterclass
Power of the Many: Digital Energy Masterclass
mariana491193
 
Company Profile [Popular Group of Industries]
Company Profile [Popular Group of Industries]
irtizashirazi
 
Ian McAllister - Respected Photographer And Writer
Ian McAllister - Respected Photographer And Writer
Ian McAllister
 
ERP Modernization in 2025: A Practical Guide for CIOs
ERP Modernization in 2025: A Practical Guide for CIOs
Praxis Info Solutions
 
SACRS_Spring Mag 2025 Graceada Article.pdf
SACRS_Spring Mag 2025 Graceada Article.pdf
matthieu81
 
Book - Behavioral finance and wealth management(1).pdf
Book - Behavioral finance and wealth management(1).pdf
GamingwithUBAID
 
Streamline Success: How Well-Defined SOPs Drive Organizational Efficiency
Streamline Success: How Well-Defined SOPs Drive Organizational Efficiency
RUPAL AGARWAL
 
What Drives Collectors in Sports and Beyond, and How Mantel is Bringing Them ...
What Drives Collectors in Sports and Beyond, and How Mantel is Bringing Them ...
Neil Horowitz
 
From Visibility to Action: How Modern Cloud Teams Regain Control
From Visibility to Action: How Modern Cloud Teams Regain Control
Amnic
 
smidmart industrial Automation Ones Stop Solution
smidmart industrial Automation Ones Stop Solution
smidmart
 
The APCO Geopolitical Radar Q3 2025 Edition
The APCO Geopolitical Radar Q3 2025 Edition
APCO
 
Enterprise Architecture Professional Journal Vol IX June 2025.pdf
Enterprise Architecture Professional Journal Vol IX June 2025.pdf
Darryl_Carr
 

Writing and Testing JavaScript-heavy Web 2.0 apps with JSUnit

  • 1. Writing and Testing JavaScript-heavy Web 2.0 apps with JSUnit Authors: Alex Chaffee, Pivotal Labs Edward Hieatt, Pivotal Labs
  • 2. Abstract With the advent of the so-called Web 2.0 platform, more and more applications are using client-side JavaScript for vital features. In fact, some applications are so JS-heavy that they redefine JavaScript as a full-fledged application development language. In this tutorial we discuss some architectural considerations of JS- and AJAX-heavy applications and present in detail our testing framework, with plenty of code examples and live demos.
  • 3. JS Application Architectures Traditional: Minimal JS JS for validation JS for user responsiveness JS for DHTML JS for layout tweaks (where CSS falls down)
  • 4. JS Application Architectures (cont.) AJAX Architecture Widgets and functions live on client Use XMLHttpRequest for immediate or background requests to server Use JSON or XML for data transport
  • 5. JS Application Architectures (cont.) Dynamic Architecture: server-generated JS RJS Google Web Toolkit Big advantage: unified codebase -> DRY Disadvantages: Latency Harder to test
  • 6. Application Architectures (cont.) Client-Server JS MVC: Heavy JS In this architecture, the JavaScript code takes the form of a full-fledged application. Using JSON to transfer data back and forth between the server-side API, the JavaScript application maintains its own domain objects and executes its own business rules. Can violate DRY
  • 7. Application Architectures (cont.) Hybrid Naturally, you can mix and match the above techniques Complicates your coding and testing Can violate DRY
  • 8. Testing Strategies Unit Testing: JSUnit Integration Testing: Selenium WATIR
  • 9. JavaScript Essence Dynamic Interpreted Prototype-based OO Object = Hash Everything (even Function) is a Hash Sort of a mutant hybrid of Java and Ruby
  • 10. JavaScript Cons Functions have loose binding “ this” isn't always correct Workaround: Use bind (part of prototype.js) Frustrating syntax and semantics Symbols are globally scoped by default You must remember “this” Too easy to make global variables null vs. undefined vs. 0 All members are public No OO inheritance Several hacks to simulate inheritance Rely more on composition Browser differences (esp. DOM API) and bugs No “include” or “require” We rolled our own Painful debugging Unreliable stack traces Two different GCs Memory leaks via DOM Third-party libraries rarely tested
  • 11. JavaScript Tools and Libraries
  • 12. Firefox Extensions Web Developer Firebug ROCKS
  • 13. Development Environments IDEA Eclipse TextMate ?
  • 14. prototype.js Library bind $ $H, $A, each, etc. extend Ajax.Request Element.hide Other useful stuff
  • 15. JS UI libraries script.aculo.us Very Good Popular (easy to find help) Yahoo UI Excellent Drag and drop, animation, calendar, etc.
  • 16. Asset Packager Combines multiple JS files into one Also CSS Reduces Latency Also Steve Conover’s inline merger looks promising
  • 17. JSUnit “ Controlling The Insanity” Unit Testing is essential for all but the most trivial JavaScript
  • 19. clock.js Testing utility class we wrote Overrides setTimeout Allows unit testing of time-based operations without sleeping
  • 20. ajax.js AjaxUnit Overrides Prototype AJAX classes Stubs out the network interface Allows unit testing of AJAX calls
  • 21. Mock Objects in JS We don’t know of any real mocking framework for JS We use stubs, spies, object mothers and mock methods
  • 23. Client-Server Communication: Let me count the ways HTTP Including GET, POST, cookies, etc. CGI AJAX+XML AJAX+JSON AJAX+HTML AJAX+JS RJS
  • 24. AJAX “ Asynchronous JavaScript And XML” Client calls server with CGI GET or POST via XMLHttpRequest API Server responds Client does something without redrawing entire page
  • 25. AJAX+XML Response contains XML Original implementation of AJAX Not used much now (?) I've heard of doing XSL but that's mostly on IE-only apps
  • 26. JSON Evaluates to JS values (hashes and arrays) Example: { "Image": { "Width": 800, "Height": 600, "Title": "View from 15th Floor", "Thumbnail": { "Url": "http: //scd.mmb1.com/image/481989943", "Height": 125, "Width": "100" }, "IDs": [116, 943, 234, 38793] } }
  • 27. AJAX+JSON (AJAJ?) Proper client-server communication Client sends requests in CGI, gets responses as pure data Client evaluates data, actively performs response Interacts with DOM Creates/removes/modifies/copies HTML elements
  • 28. AJAX+HTML Server executes RHTML/JSP/etc. AJAX response contains HTML Client splats it onto the page
  • 29. AJAX+JS AJAX response contains JavaScript code Client calls eval() on it Powerful and a little scary Hard to test
  • 30. RJS Part of Ruby on Rails Generates JS via Ruby methods Not as scary as raw JS since it’s coming from a tested library
  • 31. Latency: The AJAX killer This AJAX stuff really is client-server communication If the server is slow, your app crawls to a halt -- and inside a page, not just between pages Less user feedback for a hung AJAX call Can lead to multiple clicks, reloads, confusion, etc.
  • 32. Solving Latency The Easy Way: Use a spinny icon Still requires UI/UE design
  • 33. Solving Latency The Hard Way: To solve, you must write a lot of code on the client to react immediately to user actions, then queue up requests and deal gracefully once the server reponds Error handling Command queue Undo Dynamic/incremental data updates This leads naturally to true MVC in JS
  • 34. JS MVC Architecture JSON Model Objects Notify View Components Render DOM User Events Enqueue Command Objects Execute / undo AJAX (CGI)
  • 35. Integration Testing with Selenium Selenium… Runs in the browser Executes your app in a frame Simulates user actions via JavaScript Goes all the way to the server and back Complementary to JSUnit JSUnit tests JS pages and libraries only, not interaction with server Selenium is fun to watch Integrated into Continuous Integration like JSUnit Catch our talks on Wednesday (Selenium) and Thursday (CI)
  • 36. Q&A
  • 38. Clock We wrote our JS “Mock Clock” test-first Actually, it’s a stub, not a mock :-) Illustrates a true (isolated) unit test of a utility class
  • 39. Weaver The Weaver takes two arrays and returns the set of changes required to transform one into the other Used by Tracker’s list widgets Illustrates use of roll-your-own test spies
  • 40. DateWidget We wrapped Yahoo’s YUI Calendar widget to add a text field with validation and pop-up-on-activate Illustrates Testing with UI events Using a “demo.html” page Wrapping a third-party widget with tests
  • 41. Server Proxy Illustrates AjaxUnit (ajax.js) mocking out the networking layer
  • 42. Add Note Command Tests the command which adds a note (comment) to a story Does not test the networking layer, just the command object Demonstrates use of stubs and object mother (JsonFactory)
  • 43. Login Widget PeerToPatent uses page caching, so we have to render the “you’re logged in / please log in” area of the screen in JavaScript
  • 44. Cacheable Flash Not that kind of Flash… “Flash” is Rails for “Message Box” In order for dynamic information to be rendered inside of a statically cached page, we put it into a cookie, and render the cookie’s contents with JavaScript
  • 45. Cookie Library Illustrates testing a third-party library We found bugs in it, esp. IE 7 We had to patch it
  • 46. JS Paginator Illustrates receiving JSON with data Download (actually render) entire data set on page load, then render some at a time Doesn’t scale to large datasets, like Rico LiveGrid does
  • 47. Experimentation Since this is an agile conference, if there's time and interest, we can get volunteers from the audience to come up and pair program with the presenters on stage. solving problems posed by the audience.
  • 48. Where to find more info? http://jsunit.net http://pivotallabs.com