Unit testing the jQuery Rambling Slider - Part 2 - The DOM, jQuery and node.js
November 9, 2011
This post was originally published in the Rambling Labs Blog on November 9, 2011.
In order to continue to add tests to the jQuery Rambling Slider, I needed to test something against the DOM. Problem is, you don’t count with the DOM when you’re running the Jasmine tests from console. So what should I do?
As expected, I found that there is a DOM emulator in node.js :D. Also, to test using jQuery I needed to download the corresponding node package. So I didn’t waste any time and went ahead to install them:
npm install -g jsdom
npm install -g jquery
So now, I can write something like this in my src/jquery.plugins.coffee
:
(($) ->
$.fn.reverse = [].reverse
)(jQuery)
And test it on my spec/jquery.plugins.spec.coffee
with something like this (this is a somewhat trivial test):
global.window = require('jsdom').jsdom().createWindow()
global.jQuery = require 'jquery'
require '../src/array_extensions'
require '../src/jquery.plugins'
$ = jQuery
describe 'jQuery Plugins', ->
html_box = null
beforeEach ->
html_box = $ '<div></div>'
html_box.append '<ul><li></li><li></li><li></li><li></li></ul>'
describe 'when reversing a jQuery array', ->
original_array = null
array = null
beforeEach ->
array = html_box.find 'li'
original_array = html_box.find 'li'
array = array.reverse()
it 'should return the elements in reverse order', ->
for i in [0...array.length]
expect(array[i]).toEqual original_array[array.length - 1 - i]
Then run:
jasmine-node --coffee spec/
And that’s it! Pretty cool, huh?