Your SlideShare is downloading. ×
  • Like


Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.


Now you can save presentations on your phone or tablet

Available for both IPhone and Android

Text the download link to your phone

Standard text messaging rates apply

Java script unit testing


My talk at Community Day in Stockholm.

My talk at Community Day in Stockholm.

Published in Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads


Total Views
On SlideShare
From Embeds
Number of Embeds



Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

    No notes for slide


  • 1. ” ” ”” ” ” ” ” ” ” ” ”
  • 2. JavaScript schedulingand Gantt charts Siesta (JS Test Tool)
  • 4. How many of you...
  • 5. 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.
  • 6. ”... my code is bug free””...testing takes time away fromadding new features (+ new bugs)””’s QA’s job to test””... it’s boring and I’ll quit my job”
  • 7. Interwebs
  • 8. • Single controlled platform • Simple to test and refactor • Good IDEs and toolsPHP C# Java
  • 9. • Multiple platforms & versions (Mac, Windows XP/Vista/7, Linux...)• Multiple browser versions• Hard to refactor• JavaScript support in IDEs is still !== awesome
  • 10. • Developing frontend code is harder than developing server code.• Mainly due to lack of good tools• Lots of uncertainty, x-browser issues• IE6
  • 11. As good JS dev tools are hard to find, we need tomake good use of existing tools and practices.
  • 12. isUserCrazy: function(user, isAdmin) { // DON’T CHANGE THIS if (user.age > 35 && isAdmin!== true && isAdmin!== false) { user.crazy = true; }}
  • 13. 120100 80 60 Backend 40 Frontend 20 0 Pain of Refactoring
  • 14. ’ • iOS • Android • IE Mobile • Blackberry • Firefox mobile • ...
  • 15. • We spend lots of time debugging frontend code.• Helpful to know which parts of an application is well tested => less likely to have bugs.
  • 16. • Find bugs early• Develop & refactor with confidence• Tests serve as additional API documentation• Helps you detect tightly coupled code
  • 17. • 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?
  • 18. scripts/core/application.js/* 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 **/
  • 19. New guy, scared
  • 20. • 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?
  • 21. • Code and design for testability• Choose the tools to help you• Automation / CI / Coverage
  • 22. • 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.
  • 23. • 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
  • 24. Mixing view and business logicExt.define(UserForm, { extend: Ext.FormPanel, width: 400, height: 400, model: new UserModel(), // Returns true if User is valid isValid: function (userModel) { return > 4 && userModel.password.length > 8; }});
  • 25. Better:Ext.define(UserModel, { extend: , name : “”, password : “”, // Returns array of User model objects isValid : function () { return > 4 && this.password.length > 8; }});
  • 26. No business logic in viewExt.define(UserForm, { extend: Ext.FormPanel, width: 400, height: 400, model: new UserModel(), // Returns true if User is valid isValid: function (userModel) { return userModel.isValid(); }});
  • 27. • Avoid overuse of private functions in closures• If your code cannot be accessed it cannot be tested
  • 28. • 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
  • 29. • Jasmine• Siesta• Buster.js (beta) / Sinon.js• DOH (Dojo Object Harness)• Qunit (jQuery)• JsUnit (abandoned?)• YUI Test• Google js-test• Zombie (headless/Node)
  • 30. • 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
  • 31. • Simple DOM-less testing• BDD syntax• Borrows “the best parts” of ScrewUnit, JSSpec, JSpec, and RSpec.
  • 32. Suite / Specdescribe(panda, function () { it(is happy, function () { expect(panda).toBe(happy); });});Sourcepanda = happy; // => PASS
  • 33. • 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
  • 34. test-jquery_01.jsStartTest(function(t) { t.diag(Testing jQuery...); $(body).html(JQuery was here); t.contentLike(document.body, JQuery was here, Found correct text in DOM);});
  • 35. • 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.
  • 36. 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" });}
  • 37. • Test larger piece of your app, or the application as a whole.• Simulate user interaction, click, type etc.• Navigate between pages
  • 38. • Selenium• Funcunit• JsTestDriver• Siesta• Watir• DOH Robot (Dojo)• Sahi• Squish (Frog Logic)
  • 39. Two main approaches of faking a user • Synthetic events • Native events (via Java Applet)
  • 40. + 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 (
  • 41. + Java applets are supported in all desktopbrowsers+ As close to a ’real’ user as possible- Won’t work on iOS, Android.- No parallell tests since native event queueis used.
  • 42. ” ”Opens real browser instances and ’drives’themOutputs commands and evaluates resultCan be quite slow
  • 43. ” ”Selenium The most widely used functional testing tool. Firefox Recorder.JsTestDriver By Google. ”Remote JavaScript Console”. IntelliJ and EclipseWatir Web Application Testing in Ruby. Also a .NET port, WatiN.Sahi By TytoSoftware. Has X-browser recorder.
  • 44. • “A web browser without a graphical user interface”• Command line interface• Great for automating tests, integrating with CI tools (Jenkins, Cruise Control…)
  • 45. + Run tests on command line+ Faster+ Automation+ Doesn’t require an actual browser- Not 100% accurate, but close.
  • 46. PhantomJS (headless WebKit + JavaScript API)env.js (Runs on Rhino)JsDom (CommonJS implementation of the DOM)
  • 47. Created by Ariya Hidayat (Sencha Inc.)Fast headless testingSite scrapingSVG renderingSupports CoffeeScript
  • 48. • JsCoverage Seems abandoned• ScriptCover Google Chrome Plugin• JsTestDriver Add-in module for coverage• JesCov Rhino, Jasmine
  • 49. • 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.
  • 50. • Jenkins• Cruise Control• Test Swarm
  • 51. • 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
  • 52.
  • 53.
  • 54. ”Without unit tests, you’re not refactoring. You’re just changing shit.”Hamlet D’Arcy
  • 55.