Tuesday, October 29, 2013

Testing javascript with jasmine - Part 1



What is jasmine.js?
        
Jasmine is a behavior-driven testing framework for JavaScript and an automated testing framework for JavaScript. . It does not require a DOM.


BDD stands for Behaviour-Driven Development
TDD stands for Test Driven Development


TDD:
1.     Write your tests case
2.     Watch them fail case
3.     Make them pass case
4.     Refactor
5.     Repeat

BDD:
·       Establishing the goals of different stakeholders required for a vision to be implemented
·       Involving stakeholders in the implementation process through outside-in software development
·       Using examples to describe the behavior of the application, or of units of code
·       Automating those examples to provide quick feedback and regression testing




Jasmine on your Computer:

         Before you work on jasmine you should get jasmine on your computer.

Get jasmine standalone version here. Then unzip it, and empty out /spec and /src folders. They’re examples, you don’t need it.

In newer version, /lib folder contains jasmine.js, jasmine.css, jasmine-html.js

Let’s playing with jasmine JavaScript.


Let’s understanding Jasmine syntax:
        

describe: (Suite)

A test suite begins with a call to the global Jasmine function "describe” with two parameters: a string and a function.
·       The string is a name or title for a spec suite – usually what is under test.
·       The function is a block of code that implements the suite.


Example:

describe("A suite", function() {
    it("contains spec with an expectation", function() {
        expect(true).toBe(true);
    });
});

it: (specs)

Specs are defined by calling the global Jasmine function it, which, like describe takes a string and a function. The string is a title for this spec and the function is the spec, or test.

A spec contains one or more expectations that test the state of the code under test.



Note:
                Since describe and it blocks are functions, they can contain any executable code necessary to implement the test.
                JavaScript scoping rules apply, so variables declared in a describe are available to any it block inside the suite.

Example:

describe("A suite is just a function", function() {
    var a;
   
    it("and so is a spec", function() {
        a = true;
       
        expect(a).toBe(true);
    });
});


expect: (Expections)

                Expectations are built with the function expect which takes a value, called the actual. It is chained with a Matcher function, which takes the expected value.





Matchers:
                Each matcher implements a boolean comparison between the actual value and the expected value. It is responsible for reporting to Jasmine if the expectation is true or false. Jasmine will then pass or fail the spec.

Negative Matchers:
Any matcher can evaluate to a negative assertion by chaining the call to expect with a not before calling the matcher.

Example:

describe("The 'toBe' matcher compares with ===", function() {
   
        // matches (using postive case)
        it("and has a positive case ", function() {
            expect(true).toBe(true);
        });
   
        // Not matches (using negative case)
        it("and can have a negative case", function() {
            expect(false).not.toBe(true);
        });
});



Built-in Matchers:

//compares objects or primitives x and y and passes if they are equivalent
expect(x).toEqual(y);  

//compares objects or primitives x and y and passes if they are the same object
expect(x).toBe(y);

//compares x to string or regular expression pattern and passes if they match
expect(x).toMatch(pattern);

//passes if x is not undefined
expect(x).toBeDefined();

//passes if x is undefined
expect(x).toBeUndefined();

//passes if x is null
expect(x).toBeNull();

//passes if x evaluates to true
expect(x).toBeTruthy();

//passes if x evaluates to false
expect(x).toBeFalsy();

//passes if array or string x contains y
expect(x).toContain(y);

//passes if x is less than y
expect(x).toBeLessThan(y);

//passes if x is greater than y
expect(x).toBeGreaterThan(y);

//passes if function fn throws exception e when executed
expect(function(){fn();}).toThrow(e);


Built-in Negative Matchers:

Every matcher's criteria can be inverted by prepending “.not”:

//compares objects or primitives x and y and passes if they are not equivalent
expect(x).not.toEqual(y);


Writing New Matchers:
        
         Why new matchers?
                 In jasmine.js having small set of build-in matchers. However, we recommend that you write custom matchers when you want to assert a more specific sort of expectation.
         If we want to create new matchers in jasmine JavaScript, easily we can create it. Custom matchers helps to document the intend of your specs, and can help to remove duplicate code into your specs.

Create custom matchers:
A matcher function receives the actual value as “this.actual”, and zero or more arguments may be passed in the function call. The function should return true if the actual value passes the matcher's requirements, and false if it does not.

Example 1:

beforeEach(function() {
    this.addMatchers({
       
    toBeLessThan: function(expected) {
        var actual = this.actual;
        var notText = this.isNot ? " not" : "";
       
        this.message = function () {
            return "Expected " + actual + notText + " to be less than " + expected;
        }
       
        return actual < expected;
    }
       
    });
});

Ø  Here's the definition of toBeLessThan()
Ø  To add the matcher to your suite, call this.addMatchers() from within a before or it block.
Ø  To customize the failure message, inside the matching function assign this.message to be a function returning the desired message.
Ø  Use this.isNot to make the message correct in the negative case

Example 2:

beforeEach(function () {
    this.addMatchers({
    toBeBetween: function (rangeFloor, rangeCeiling) {
        if (rangeFloor > rangeCeiling) {
            var temp = rangeFloor;
            rangeFloor = rangeCeiling;
            rangeCeiling = temp;
        }
        return this.actual > rangeFloor && this.actual < rangeCeiling;
    }
    });
});


Output 2:

it("is between 5 and 30", function () {
    expect(10).toBeBetween(5, 30);
});

it("is between 30 and 500", function () {
    expect(100).toBeBetween(500, 30);
});

Note:
The describe function is for grouping related specs. The string parameter is for naming the collection of specs, and will be concatenated with specs to make a spec’s full name.

Setup and Teardown:        
Setup and teardown code should be placed in the global beforeEach() and afterEach() methods. These are useful for reinitializing and setting test values between tests.
 The beforeEach() method is called before each spec (it() method) in the describe and afterEach() is called after each spec.

Example:

describe("Stock Portfolio App Tests", function() {
    var presentValue,
    previousValue,
    aPercentChanges;
   
    beforeEach(function() {
        presentValue    = 110;
        previousValue   = 100;
        aPercentChanges = [];
    });
   
    afterEach(function() {
        presentValue    = 0;
        previousValue   = 0;
        aPercentChanges = [];
    });
   
    // The beforeEach() method is called before each spec - it() method in the describe
    it("calcWeeklyPercentChange() should return the change between two numbers as a percentage.", function() {
        var calcWeeklyPercentChange = function(presentValue, previousValue, aPercentChanges) {
            var percentChange = presentValue / previousValue - 1;
            aPercentChanges.push(percentChange);
            return percentChange;
        };
       
        //actually returns 0.10000000000000009!
        var result = calcWeeklyPercentChange(presentValue, previousValue, aPercentChanges);
        expect(result).toBeCloseTo(0.1);
        expect(aPercentChanges.length).toEqual(1);
    });
    // The afterEach() method is called after each spec - it() method in the describe

   
    //So you will get aPercentChanges.length = 0
    it("The aPercentChanges array should now be empty.", function() {
        expect(aPercentChanges.length).toEqual(0);
    });
});

Note:

Nested Describe:

         Jasmine allows to use nested describe.  This allows a suite to be composed as a tree of functions.
Before a spec is executed, Jasmine walks down the tree executing each beforeEach function in order. After the spec is executed, Jasmine walks through the afterEach functions similarly.

Disabling Specs and suites:


Suites and specs can be disabled with the xdescribe and xit functions, respectively. These suites and specs are skipped when run and thus their results will not appear in the results.

No comments:

Post a Comment