• Like
  • Save

Loading…

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.

Like this presentation? Why not share!

Java script unit testing

on

  • 4,488 views

My talk at Community Day in Stockholm.

My talk at Community Day in Stockholm.

Statistics

Views

Total Views
4,488
Views on SlideShare
4,475
Embed Views
13

Actions

Likes
3
Downloads
71
Comments
0

3 Embeds 13

https://twitter.com 6
http://a0.twimg.com 4
http://www.linkedin.com 3

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Java script unit testing Java script unit testing Presentation Transcript

    • ” ” ”” ” ” ” ” ” ” ” ”
    • JavaScript schedulingand Gantt charts Siesta (JS Test Tool)
    • </SELFPROMOTION>
    • How many of you...
    • 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.
    • ”... my code is bug free””...testing takes time away fromadding new features (+ new bugs)””...it’s QA’s job to test””... it’s boring and I’ll quit my job”
    • Interwebshttp://www.app.com
    • • Single controlled platform • Simple to test and refactor • Good IDEs and toolsPHP C# Java
    • • Multiple platforms & versions (Mac, Windows XP/Vista/7, Linux...)• Multiple browser versions• Hard to refactor• JavaScript support in IDEs is still !== awesome
    • • 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 tomake good use of existing tools and practices.
    • isUserCrazy: function(user, isAdmin) { // DON’T CHANGE THIS if (user.age > 35 && isAdmin!== true && isAdmin!== false) { user.crazy = true; }}
    • 120100 80 60 Backend 40 Frontend 20 0 Pain of Refactoring
    • ’ • iOS • Android • IE Mobile • Blackberry • Firefox mobile • ...
    • • We spend lots of time debugging frontend code.• Helpful to know which parts of an application is well tested => less likely to have bugs.
    • • Find bugs early• Develop & refactor with confidence• Tests serve as additional API documentation• Helps you detect tightly coupled code
    • • 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?
    • 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 **/
    • New guy, scared
    • • 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?
    • • Code and design for testability• Choose the tools to help you• Automation / CI / Coverage
    • • 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.
    • • 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
    • 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 userModel.name.length > 4 && userModel.password.length > 8; }});
    • Better: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; }});
    • 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(); }});
    • • Avoid overuse of private functions in closures• If your code cannot be accessed it cannot be tested
    • • 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
    • • Jasmine• Siesta• Buster.js (beta) / Sinon.js• DOH (Dojo Object Harness)• Qunit (jQuery)• JsUnit (abandoned?)• YUI Test• Google js-test• Zombie (headless/Node)
    • • 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
    • • Simple DOM-less testing• BDD syntax• Borrows “the best parts” of ScrewUnit, JSSpec, JSpec, and RSpec.
    • Suite / Specdescribe(panda, function () { it(is happy, function () { expect(panda).toBe(happy); });});Sourcepanda = happy; // => PASS
    • • 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
    • 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);});
    • • 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.
    • 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" });}
    • • Test larger piece of your app, or the application as a whole.• Simulate user interaction, click, type etc.• Navigate between pages
    • • Selenium• Funcunit• JsTestDriver• Siesta• Watir• DOH Robot (Dojo)• Sahi• Squish (Frog Logic)
    • Two main approaches of faking a user • Synthetic events • Native events (via Java Applet)
    • + 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)
    • + 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.
    • ” ”Opens real browser instances and ’drives’themOutputs commands and evaluates resultCan be quite slow
    • ” ”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.
    • • “A web browser without a graphical user interface”• Command line interface• Great for automating tests, integrating with CI tools (Jenkins, Cruise Control…)
    • + Run tests on command line+ Faster+ Automation+ Doesn’t require an actual browser- Not 100% accurate, but close.
    • PhantomJS (headless WebKit + JavaScript API)env.js (Runs on Rhino)JsDom (CommonJS implementation of the DOM)
    • Created by Ariya Hidayat (Sencha Inc.)Fast headless testingSite scrapingSVG renderingSupports CoffeeScript
    • • JsCoverage Seems abandoned• ScriptCover Google Chrome Plugin• JsTestDriver Add-in module for coverage• JesCov Rhino, Jasmine
    • • 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.
    • • Jenkins• Cruise Control• Test Swarm
    • • 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
    • http://www.adequatelygood.com/2010/7/Writing-Testable-JavaScripthttp://blog.jcoglan.com/2011/07/14/refactoring-towards-testable-javascript-part-1/
    • http://screen.yahoo.com/
    • ”Without unit tests, you’re not refactoring. You’re just changing shit.”Hamlet D’Arcy