JavaScript Unit-Testing Mihail Irintchev SiteGround.com
How do you test your JS? 1. Write your JavaScript code 2. See if it works in your favourite browser 3. Change something + [F5] 4. If it doesn't work repeat #3 until you make it work or you go crazy... 5. In case you made it work, discover few days/weeks later that it doesn't work in another browser
I think I'm going crazy...
So what's the first step to sanity? WRITE TESTABLE CODE
What's wrong with this code? js_sample_001.js (inline functions and more inside, ajax directly hooked to element, etc.)
Anonymous functions, within functions, within functions...
I'll put functions in your functions...
All your DOM elements are belong to JS!
Server URL coupling js_sample_001.js (with highlighted hardcoded url)
Refactoring... js_sample_002.js
Refactoring... js_sample_002.js
Now that's better... js_sample_003.js (init func and hooked named functions to page)
Now that's better...
Now that's better...
Now what about testing? Popular JS Unit-testing frameworks:  QUnit  Jasmine  UnitJS  JsUnit (no longer actively maintained)  Some other – see: http://en.wikipedia.org/wiki/List_of_unit_testing_frameworks#JavaScript
What's about QUnit?  Used by the jQuery project to test jQuery, jQuery UI, jQuery Mobile  Can be used to test any generic JavaScript code, including itself  Very easy to install – just include JS & CSS file in your HTML
Minimal setup: The tests.htm file
The tests.js file ...remember this earlier?
… and the results:
More tests: quite a variety
… and the results:
Test modules ... and the results page:
Setup / TearDown methods:
What about asynch methods & AJAX? Use an AJAX mocking library, such as jquery-mockjax:
No bullshit Let me show you...
Other mock JS frameworks: -ajax
But what about test automation?
Why phing? 1. Because I like it and I am used to it, and... 2. PHING ALL THE THINGS!
But phing runs in the console... JS needs browser to run in... How do we run the browser? Wouldn't it be slow?
Need speed? Ditch the browser!
But what about cross-browser testing?
Credits ”Browser Eyeballing != JavaScript Testing”, Jordan Kasper bit.ly/js-testing ”Unit Testing JavaScript With QUnit And Phing”, Robert Price http://www.robertprice.co.uk/robblog/2012/12/unit-testing-javascript-with-qunit-and-phin ”Qunit Phing Task”, Martin Jonsson http://github.com/martinj/phing-task-qunit
Questions? @irintchev m.irintchev@siteground.com

Js unit testing