Learning Jasmine @ Houston.js

@ Houston.js – Learned Jasmine real quick

Overview

Jasmine is a Testing Tool for JavaScript

Classes Under Test

Classes under test as follows

var CrewMember = function (name) {
    this.name = name;
}

var Ship = function (name) {
    this.name = name;
    this.crew = [];
    this.goWarp = function () {
        console.log("Going Wrap");
    }

    this.notifyWhenOutofWarp = function(callback){
        setTimeout(callback, 1000);
    }
}

Simplest Test

describe("Crew Member", function () {
    var crew = null;

    beforeEach(function () {
        crew = new CrewMember("Kirk");
    });

    it("should have a name", function () {
        expect(crew.name).toEqual("Kirk");
    });

});

Spy, Run, Wait Feature of Jasmine

describe("Ship", function () {
    var crew = null;
    var ship = null;

    beforeEach(function () {
        crew = new CrewMember("Kirk");
        ship = new Ship("Enterprise");
        spyOn(ship, 'goWarp');
        ship.crew.push(crew);
    });

    it("should have a crew", function () {
        expect(ship.crew.length).toEqual(1);
    });
    it("should go to Warp", function () {
        ship.goWarp();
        expect(ship.goWarp).toHaveBeenCalled();
    });

    it("should call callback when notifyWhenOutofWarp is done", function(){
       var flag = false;
       runs(function() {
           ship.notifyWhenOutofWarp(function() {
               flag = true;        
           });
       });
       waitsFor(function() {
           return flag;
       }, "The notifyWhenOutofWarp(callback) call succeeded", 2000);

       runs(function() {
           expect(flag).toEqual(true);
       });

    });

});

Running Example

View this on JSFiddle