Testing Ext JS & Sencha Touch              2012 Mats Bryntse              @bryntum
Contents• Why test your JavaScript?• Testing Methodologies• Introducing Siesta• Writing testable JS• Automating tests
About mevar me = {   name        : ”Mats Bryntse”,   age         : 35+,   lives       : ”Helsingborg, Sweden”,   does     ...
What we doExt JS/ST Components                       Siesta (JS Test Tool)
First, a quick raise of        hands:  How many of you...
How many of you...• have a frontend test suite?• have frontend test suite as part of your CI?• run your test suite in all ...
Why test yourJavaScript?
A typical web app...                     Interwebshttp://www.app.com
The backend         • Single controlled platform         • Simple to test and refactor         • Good IDEs and toolsPHP   ...
The frontend• Multiple platforms & versions  (Mac, Windows XP/Vista/7/8, Linux...)• Multiple browser versions• Hard to ref...
ConclusionToo easy to #FAIL as a frontend developerTesting helps you keep fails to a minimum.
But...”... my code is bug free””...testing takes time away from adding newfeatures (+ new bugs)””...it’s QA’s job to test”...
A good investment• Writing tests === investment in your code• Takes time• Will pay you back, though not instantly
Scenario:A nasty bug was found      3 options
[panic]
[patch it]
[proper fix]
A test suite...=> confidence in your code=> serves as extra documentation=> easier refactoring=> bugs happen once, easier ...
Code handover• Test cases are really useful when handing over  responsibility for a JS module• Developer Bob quits his job...
New guy studies codebase application.js /**  * When I wrote this, only God and I understood what I was doing  * Now, God o...
Code handoverNew guy, scared
Code handover• Without test suite, will new guy feel good  about making major changes?• Only minor cosmetic changes on the...
JS TestingMethodologies
Unit testingIntegration testingFunctional testing
Unit testing• Testing the API of a single isolated ’unit’• Typically pure JS, non UI / DOM    •   verify set/get method of...
Unit testing• Siesta• Jasmine• QUnit (jQuery)• Google js-test (V8)
Integration testing• Testing integration between units.• E.g. verify cell editing plugin works in  GridPanel
Functional Web testing• UI testing of a component or an application  as a whole.• Send commands to the web page and  evalu...
Functional Web testing• Siesta• Selenium• JsTestDriver
Interacting with the DOM Approaches to faking user input  • Synthetic events (JavaScript)  • Native events (via Java Applet)
Synthetic events+ Supported in all major browsers+ Compatible with mobile+ Don’t rely on native event queue     Tests can ...
Native events+ Java applets are supported in desktopbrowsers+ As close to a ’real’ user as possible- Won’t work on iOS, An...
What is Siesta?• Unit testing and DOM testing tool• Optimized for Ext JS & Sencha Touch   - also supports jQuery, NodeJS, ...
Siesta Browser Harness
Siesta Browser Harness• A UI for Siesta, view DOM, inspect assertions• Define a tree of tests, in logical groups• Global s...
A Siesta Test• is pure JavaScript, no magic.StartTest(function(t) {      $(body).html(JQuery was here);      t.contentLike...
A Siesta Test• is completely isolated in its own iframe   (no teardown, cleanup required)
A Siesta Test• can be extended with your own custom  assertions and helper methodsStartTest(function(myTest) {    var app ...
Lifecycle of a UI testSetup      create grid, load storesWait       for store to load, grid rows to renderSimulate   click...
Setupvar userGrid = new My.UserGrid({ … });userGrid.render(Ext.getBody());
Waitt.waitForRowsVisible(userGrid, function(){    // Do something});t.waitForComponentQuery(“formpanel > textfield”);t.wai...
Simulate// A list of actions to simulatet.chain(     {           desc            : Should click trigger field,           a...
Verifyt.is(userStore.getCount(), 5, ”5 users found”);t.willFireNTimes(store, 2, ”write”);t.hasCls(grid.getEl(), ”myClass”,...
DEMO
Sencha Touch supportSimulate tap, doubleTap, swipe, longPress, etc...
Siesta.next• Benchmarking• Code coverage• Multi-browser, multi-device testing• Crowd sourced test case tool “Code Cowboy”•...
Headless testing• Headless browsers are great, fast• Command line, easy to integrate with IDEs• PhantomJS, GUI-less WebKit...
Phantom JSCreated by Ariya Hidayat (Sencha Inc.)Fast headless testingSite scrapingSVG rendering, PDF/PNG outputSupports Co...
Headless browsers+ Run tests on command line+ Faster+ Automation+ Doesn’t require an actual browser- Not 100% accurate, bu...
Writing testable JS
Some ground rules• Keep your JavaScript in JS files• Never put JavaScript in your HTML  page/tags• Keep code organized in ...
No no no
Testable MVC code• Fat model, skinny view• Don’t pollute your views with business logic• Testing pure JS is a lot easier t...
Mixing view and logicExt.define(UserForm, {    extend: Ext.FormPanel,    width: 400,    height: 400,      // Returns true ...
BetterExt.define(UserModel, {    extend: Ext.data.Model ,    name : ,    password : ,      isValid : function () {        ...
Refactored viewExt.define(UserForm, {    extend: Ext.FormPanel,    width: 400,    height: 400,      // Returns true if Use...
Avoid private code• Avoid overuse of private functions in  closures• If your code cannot be accessed it cannot  be tested
Testing Ajax• Try to avoid involving your database.• Use either static JS files with mock data  (async, slower)• Or Mock t...
Automation &Continuous Integration
Continuous Integration• Once you have decided on your testing  toolset, integrate it with your CI.• Automatically run test...
CI Tools• Jenkins• TeamCity• Cruise Control• Test Swarm
JS Code Coverage• JsCoverage   Seems abandoned• ScriptCover   Google Chrome Plugin• JsTestDriver   Add-in module for cover...
Resources - Yahoohttp://screen.yahoo.com/
Resources - GTAC
”Without unit tests, you’re         not refactoring. You’re just         changing shit.”Hamlet D’Arcy
Thanks for listening!     Questions?                  2012 Mats Bryntse                  @bryntum
Testing Ext JS and Sencha Touch
Upcoming SlideShare
Loading in...5
×

Testing Ext JS and Sencha Touch

9,829

Published on

My SourceDevCon 2012 presentation slides.

Published in: Technology
0 Comments
4 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
9,829
On Slideshare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
103
Comments
0
Likes
4
Embeds 0
No embeds

No notes for slide

Testing Ext JS and Sencha Touch

  1. 1. Testing Ext JS & Sencha Touch 2012 Mats Bryntse @bryntum
  2. 2. Contents• Why test your JavaScript?• Testing Methodologies• Introducing Siesta• Writing testable JS• Automating tests
  3. 3. About mevar me = { name : ”Mats Bryntse”, age : 35+, lives : ”Helsingborg, Sweden”, does : ”Runs Bryntum”, site : ”www.bryntum.com”, twitter : ”@bryntum”};
  4. 4. What we doExt JS/ST Components Siesta (JS Test Tool)
  5. 5. First, a quick raise of hands: How many of you...
  6. 6. How many of you...• have a frontend test suite?• have frontend test suite as part of your CI?• run your test suite in all major browsers?• have zero or fewer frontend tests for your app?
  7. 7. Why test yourJavaScript?
  8. 8. A typical web app... Interwebshttp://www.app.com
  9. 9. The backend • Single controlled platform • Simple to test and refactor • Good IDEs and toolsPHP C# Java
  10. 10. The frontend• Multiple platforms & versions (Mac, Windows XP/Vista/7/8, Linux...)• Multiple browser versions• Hard to refactor• JavaScript support in IDEs is still !== awesome
  11. 11. ConclusionToo easy to #FAIL as a frontend developerTesting helps you keep fails to a minimum.
  12. 12. But...”... my code is bug free””...testing takes time away from adding newfeatures (+ new bugs)””...it’s QA’s job to test””... it’s boring and I’ll quit my job”
  13. 13. A good investment• Writing tests === investment in your code• Takes time• Will pay you back, though not instantly
  14. 14. Scenario:A nasty bug was found 3 options
  15. 15. [panic]
  16. 16. [patch it]
  17. 17. [proper fix]
  18. 18. A test suite...=> confidence in your code=> serves as extra documentation=> easier refactoring=> bugs happen once, easier to find=======> quality of sleep
  19. 19. Code handover• Test cases are really useful when handing over responsibility for a JS module• Developer Bob quits his job. New guy gets responsibility of his JS code.• How will new guy know what parts of the codebase is safe to change & refactor?
  20. 20. New guy studies codebase application.js /** * When I wrote this, only God and I understood what I was doing * Now, God only knows **/ /* I am not sure if we need this, but too scared to delete. */ // drunk, fix later // This is my last day...
  21. 21. Code handoverNew guy, scared
  22. 22. Code handover• Without test suite, will new guy feel good about making major changes?• Only minor cosmetic changes on the surface.• System accumulates cruft over time.• Sounds familiar?
  23. 23. JS TestingMethodologies
  24. 24. Unit testingIntegration testingFunctional testing
  25. 25. Unit testing• Testing the API of a single isolated ’unit’• Typically pure JS, non UI / DOM • verify set/get method of a Model • verify date manipulation logic• Many tools available
  26. 26. Unit testing• Siesta• Jasmine• QUnit (jQuery)• Google js-test (V8)
  27. 27. Integration testing• Testing integration between units.• E.g. verify cell editing plugin works in GridPanel
  28. 28. Functional Web testing• UI testing of a component or an application as a whole.• Send commands to the web page and evaluate result.• ’click button’, ’type into login field’, ...
  29. 29. Functional Web testing• Siesta• Selenium• JsTestDriver
  30. 30. Interacting with the DOM Approaches to faking user input • Synthetic events (JavaScript) • Native events (via Java Applet)
  31. 31. 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)
  32. 32. Native events+ Java applets are supported in desktopbrowsers+ As close to a ’real’ user as possible- Won’t work on iOS, Android.- No parallell tests since native event queueis used.
  33. 33. What is Siesta?• Unit testing and DOM testing tool• Optimized for Ext JS & Sencha Touch - also supports jQuery, NodeJS, or any JS• Simple syntax, Extensible• Automate using PhantomJS & Selenium.
  34. 34. Siesta Browser Harness
  35. 35. Siesta Browser Harness• A UI for Siesta, view DOM, inspect assertions• Define a tree of tests, in logical groups• Global settings for the test suite autoCheckGlobals, preload, testClass
  36. 36. A Siesta Test• is pure JavaScript, no magic.StartTest(function(t) { $(body).html(JQuery was here); t.contentLike(document.body, JQuery was here, Found correct text in DOM);});
  37. 37. A Siesta Test• is completely isolated in its own iframe (no teardown, cleanup required)
  38. 38. A Siesta Test• can be extended with your own custom assertions and helper methodsStartTest(function(myTest) { var app = myTest.startApplication(); myTest.performLogin(app); myTest.isLoggedIn(app, ’Logged in ok’); myTest.is(app.nbrUsers, 1, ’Found 1 user’);});
  39. 39. Lifecycle of a UI testSetup create grid, load storesWait for store to load, grid rows to renderSimulate click button, type into textboxVerify isEqual(a, b)
  40. 40. Setupvar userGrid = new My.UserGrid({ … });userGrid.render(Ext.getBody());
  41. 41. Waitt.waitForRowsVisible(userGrid, function(){ // Do something});t.waitForComponentQuery(“formpanel > textfield”);t.waitForCompositeQuery(“grid => .x-grid-row”);
  42. 42. Simulate// A list of actions to simulatet.chain( { desc : Should click trigger field, action : click, target : testgrid triggerfield }, { desc : Should type into filter field, action : type, target : testgrid triggerfield, text : FOO }, ...);
  43. 43. Verifyt.is(userStore.getCount(), 5, ”5 users found”);t.willFireNTimes(store, 2, ”write”);t.hasCls(grid.getEl(), ”myClass”, ”Found CSS”);t.hasSize(myWindow, 300, 300, ”Window size ok”);
  44. 44. DEMO
  45. 45. Sencha Touch supportSimulate tap, doubleTap, swipe, longPress, etc...
  46. 46. Siesta.next• Benchmarking• Code coverage• Multi-browser, multi-device testing• Crowd sourced test case tool “Code Cowboy”• Your suggestion?
  47. 47. Headless testing• Headless browsers are great, fast• Command line, easy to integrate with IDEs• PhantomJS, GUI-less WebKit browser
  48. 48. Phantom JSCreated by Ariya Hidayat (Sencha Inc.)Fast headless testingSite scrapingSVG rendering, PDF/PNG outputSupports CoffeeScript
  49. 49. Headless browsers+ Run tests on command line+ Faster+ Automation+ Doesn’t require an actual browser- Not 100% accurate, but close.
  50. 50. Writing testable JS
  51. 51. Some ground rules• 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.
  52. 52. No no no
  53. 53. Testable MVC code• 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
  54. 54. Mixing view and logicExt.define(UserForm, { extend: Ext.FormPanel, width: 400, height: 400, // Returns true if User is valid isValid: function (userModel) { return userModel.name.length > 4 && userModel.password.length > 8; }});
  55. 55. BetterExt.define(UserModel, { extend: Ext.data.Model , name : , password : , isValid : function () { return this.name.length > 4 && this.password.length > 8; }});
  56. 56. Refactored viewExt.define(UserForm, { extend: Ext.FormPanel, width: 400, height: 400, // Returns true if User is valid isValid: function () { return this.model.isValid(); }});
  57. 57. Avoid private code• Avoid overuse of private functions in closures• If your code cannot be accessed it cannot be tested
  58. 58. Testing Ajax• Try to avoid involving your database.• Use either static JS files with mock data (async, slower)• Or Mock the entire Ajax call (sync, faster) Sinon.js, Jasmine-ajax etc.
  59. 59. Automation &Continuous Integration
  60. 60. Continuous Integration• Once you have decided on your testing toolset, integrate it with your CI.• Automatically run test suite on pre-commit or post-commit• Nightly builds, full test suite execution, reporting via email etc.
  61. 61. CI Tools• Jenkins• TeamCity• Cruise Control• Test Swarm
  62. 62. JS Code Coverage• JsCoverage Seems abandoned• ScriptCover Google Chrome Plugin• JsTestDriver Add-in module for coverage• JesCov Rhino, Jasmine
  63. 63. Resources - Yahoohttp://screen.yahoo.com/
  64. 64. Resources - GTAC
  65. 65. ”Without unit tests, you’re not refactoring. You’re just changing shit.”Hamlet D’Arcy
  66. 66. Thanks for listening! Questions? 2012 Mats Bryntse @bryntum
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×