Node.js: Unit Testing with Jasmine framework

14 / May / 2013 by Sahil Chitkara 0 comments

Jasmine is a framework which is used for testing node.js code or javascript code.

Installation

To install the latest official version, use NPM:

[js]npm install jasmine-node -g[/js]

Write the specifications for your code in *.js and *.coffee files in the spec/ directory

Execution

After installing the npm package, you can run it with:

[js]jasmine-node spec/filename.js
jasmine-node spec/filename.coffee[/js]

For executing multiple test files you can provide multiple filenames as an argument to jasmine-node command.
Key features :

  1. Behavior driven.
  2. It does not require DOM for testing.
  3. Clean and obvious syntax.

Test Cases :

SUITES
Call to a global function ‘describe’ which takes arguments a String and function. The function is a block of code that implements the suite.The String describes the title for the suit.

SPECS
Call to 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 examine the state of the code under test,their can be as many ‘it’ functions in describe block.

EXPECTATION
Expectation in jasmine is an assertion which results either true or false. Their can be as many assertions in a spec. Expectations are genrated with the function ‘expect’ which takes an argument which is the actual value. It is chained with a Matcher function, which takes the expected value.

MATCHERS

Each matcher implements the Boolean comparison between actual and expected value. Matchers are used to compare both the values and if all matchers matches or return true only then test is considered as passed else it is considered as failure. Some of the matchers functions are ‘toBe’, ‘toBeTruthy’ etc.
Some examples are as follows:

[js]expect(x).toEqual(y); // compares objects or primitives x and y and passes if they are equivalent
expect(x).toBe(y); // compares objects or primitives x and y and passes if they are the same object
expect(x).toMatch(pattern); //compares x to string or regular expression pattern and passes if they match[/js]

beforeEach() and afterEach()

Function ‘beforeEach’ performs task that is to be performed before test begins and ‘afterEach’ performs task that is to be performed after test finished execution.

Sample test

[js]
describe(“A suite”, function() {
var a;

it(“A spec”, function() {
a = true;

expect(a).toBe(true);
expect(a).not.toBe(false);
});
});
[/js]

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *