Jasmine for Unit Test Cases

This blog explains how Jasmine can be used for Unit Testing.

Jasmine is a behavior-driven development framework for testing JavaScript code. The beauty of Jasmine is that, it does not depend on any other JavaScript frameworks & does not require a DOM.

To understand more about Jasmine check out

  1. http://jasmine.github.io/2.4/introduction.html
  2. http://jasmine.github.io/

Unit Test Case is a part of Software Development Process in which the smallest testable parts of an application, called units, are individually and independently scrutinized for proper operation. Unit tests are typically written and run by software developers to ensure that code meets its design and behaves as intended. Jasmine has a clean, obvious syntax so that you can easily write tests.

Before actually jumping to syntax and use cases of “Jasmine for Unit Testing’, let’s understand what is Behavior Driven Development (BDD).

Behavior Driven testing is an extension of TDD. "Test-driven development" refers to a style of programming in which three activities are tightly interwoven: coding, testing (in the form of writing unit tests) and design (in the form of refactoring).

Like in TDD in BDD also we write tests first and the add application code. The major difference that we get to see here are

  1. Tests are written in plain descriptive English type grammar
  2. Tests are explained as behavior of application and are more user focused
  3. Using examples to clarify requirements

Check out http://toolsqa.com/cucumber/behavior-driven-development/ for broad understanding of TDD & BDD

Now let's see how to use Jasmine.

Starting Step - Download the Package

It is a standalone distribution, go to the github jasmine package page and download it. URL: "https://github.com/jasmine/jasmine"

Components

The key components of Jasmine Syntax - Suites, Specs, Expectations and Matchers

Suites

To test the code or checking project steps using jasmine.

Create a jasmine with the syntax

"describe"

It begins with a call to the global Jasmine function which describe the two parameters:

"string" and "function"

The string is a name or title for a spec suite it is a wording that what is being tested.

The function is a block of code that implements the suite or testing the code.

Specs

It is defined by calling the global Jasmine function "it".

The Syntax will be like this

//////////////////////////////////////////////////////
describe("About the main process", function(){
   it("about the function", function(){
       a = true;
       expect(a).toBe(true);
   });
});
//////////////////////////////////////////////////////

Expectations

Expectations is described as "expect" inside the function which takes a value, called the actual value as "toBe". An expectation in Jasmine is an assertion that is either true or false. 

Matchers

It is a comparison between the actual value and the expected value either if the expectation is "true" or "false".

It is used in CHATBOT Applications, Headless AngularJS scripts for mobile applications etc.,

Use Cases

A sample case is below:

User searches for an address in location search using google directions API

User Behaviour

  1. Enter Search Details
  2. Click on Search Button

API Integration points:

  1. Send the address information to google map API
  2. Then get response from the google map API

Here we can check with the response value from the directions API against the expected value.

describe('get google directions', function () {
  it("should respond with direction detail", function (done) {
       userdata = { 'body': 'Hi' };
    })
    .then(function (params) {
       expect(askDestination).toBe(googledirection.askOrigin);
       userdata = {
              'body': 'tambaram'
       };
      return askDestination(userdata);
    })
    .then(function (params) {
        expect(askDestination).toBe(googledirection.askDestination);
        userdata = {
             'body': 'egmore',
             googledirection: {
                      'origin': 'tambaram'
             }
       };
      return askDestination(userdata);
    })
    .then(function (params) {
        expect(askMapImageNeed).toBe(googledirection.askMapImageNeed);
        userdata = {
            'body': 'yes',
             googledirection: {
                      'origin': 'tambaram',
                      'destination': 'egmore'
              }
         };
         return getDirectionOverview(userdata);
    })
    .fail(function (error) {
         console.log(error);
    });
});

 

How to run the Jasmine?

Step 1:

Install the jasmine js.

Using the Node package manager install jasmine module.

Run the command line prompt

Choose the folder path in the cmd prompt

CMD: “npm install jasmine

Then

CMD: “jasmine init

Step 2:

Create a folder called spec inside the project root folder

Step 3:

Run the command line prompt

Choose the folder path in the cmd prompt

Step 4:

Add the file testcasefile.js inside the spec folder.

Step 5:

Then run the below mentioned command

jasmine spec/testcasefile.js

Response

1. If you are running single spec i.e., it function in a describe function. It will respond like below.

Result: “1 test, 1 assertion, 0 failures, 0 pending spec

2. If you are running 3 spec with multiple it functions in a describe function. It will respond like below.

Result: “3 tests, 6 assertions, 1 failure, 2 pending spec” 

3. If you need to skip any particular spec just update it to xit.

Result: “3 tests, 8 assertions, 1 failure, 1 pending spec, 1 skipped

In the result

tests” are the total no. of spec (it) functions in a describe function.

assertion” is the expectation (expected value) of the result on a particular step.

failure” is the failed case of the result on a particular step.

pending spec” is the case in which the spec is still waiting for the execution.

skipped” is the case where it is defined by an user in which change the it function to xit If the function is not necessary for the execution.

In today’s world of Headless Drupal, Device agnostic development, Chatbots we embrace the use of many javascript frameworks. It is important that the development also has a BDD testing aligned to ensure an out-side in methodology.

Popular BDD tools used in Drupal include: Behat, Spec and Simple Text Fixtures.

Here's a link on Drupal 7 module for integration between Drupal, Jasmine JS and Phantom

Check out below links for other interesting topics on Jasmine.

  1. http://howtodoinjava.com/scripting/javascript/jasmine-javascript-unit-testing-tutorial/
  2. https://code.tutsplus.com/tutorials/testing-your-javascript-with-jasmine--net-21229
  3. https://www.distelli.com/docs/tutorials/test-your-nodejs-with-jasmine