(R)Spec for JavaScript

Posted by Laurynas Liutkus 01/01/2008 at 22h39

With the new year comes a new hope for You, JavaScript developer! Have you ever wanted to test whether your function calls AJAX properly? Or some Effect? Now you can. Just set up JsUnit, download spec.js, include it into your test html and try this:

function testAjax() {
  expect_create(Ajax.Request).with_params(['/my/url', {asynchronous: true, evalScripts: true, parameters: {a: 'b'}}]);

  new Ajax.Request('/my/url', {asynchronous: true, evalScripts: true, parameters: {a: 'b'}});
}

While this snippet looks quite nice (except for square brackets - I haven't decided whether to remove them or not), it still needs something. Setup and teardown - JSUnit runs setUp before and tearDown after every test.

function setUp() {
  RSpec.setUp();
}

function tearDown() {
  RSpec.tearDown();
}

What was actually tested in the first snippet, was class creation with specified parameters. But what if you have an object with some very complex method and only need to be sure it is called. You don't care what will it do. Let's go!

// let's create a class
var Ship = Class.create({
  shoot = function(target) {
    alert('shooting specified target');
    new Ajax.Request(...);
  }
});

// add testing methods for instances of Ship
Ship.addMethods(RSpecMethods);

// now our test
function testAttack() {
  ship = new Ship();
  ship.should_receive('shoot').with_params(['Deathstar']);

  //replace following line with simulated click event or something similar
  ship.shoot('Deathstar');
}
Got crazy? Don't specify any params, but specify how many times to expect:
ship.should_receive('shoot').exactly(5);

ship.shoot('Deathstar');
ship.shoot('Norad II');
ship.shoot('Moon');
ship.shoot('Deathstar');
ship.shoot('params', 'count', 'is', {not: 'checked'});

2 comments | no trackbacks

Comments

  1. Artūras Šlajus said 14/05/2008 at 16h20 later:

    http://www.rubyonrails.lt/files/spec.js

    truksta..

  2. TJ Holowaychuk said 18/08/2009 at 00h06 later:

    http://jspec.info :P

Trackbacks

Use the following link to trackback from your own site:
http://www.rubyonrails.lt/trackbacks?article_id=25

(leave url/email »)

reCaptcha

   Comment Markup Help Preview comment