Unit testing using Jasmine

Jasmine is an open source framework, which is the most popular choice for unit testing of AngularJS applications. Jasmine is a framework for JavaScript test driven development. Jasmine provides functions and assertions to structure the test. Jasmine can be executed on any JavaScript-enabled framework, as it does not require any integrated development environment (IDE).

The Jasmine framework is informal to read. Let's assume that we have a helloWorld() function for which we want to write a test using Jasmine. The following is the unit test code:

describe('Hello world', function() {

  it('says hello', function() {

    expect(helloWorld()).toEqual("Hello world!");

  });

});

In the preceding code the describe() function is known as a suite of tests and the it() function is an individual test specification used with the JavaScript function to figure out what the helloWorld() function will do. As you can see in the preceding example, if helloWorld() is not equal to Hello World!, then this is called a matcher. Jasmine provides the following matchers:

  • toThrow(e);
  • toBe(instance);
  • toBeDefined();
  • toBeFalsy();
  • toBeGreaterThan(number);
  • toBeLessThan(number);
  • toBeNull();
  • toBeTruthy();
  • toBeUndefined();
  • toContain(member);
  • toContain(substring);
  • toEqual(mixed);
  • expect(mixed).toMatch(pattern);

Jasmine has built-in matchers, but we can also make our own matchers; the following code shows the example of a custom Jasmine matcher:

describe('Hello world', function() {

  beforeEach(function() {

    this.addMatchers({

      toBeDivisibleByTwo: function() {

        return (this.actual % 2) === 0;

      }

    });

  });

  it('is divisible by 2', function() {

    expect(gimmeANumber()).toBeDivisibleByTwo();

  });

});

We can see in the preceding code that the toBeDivisibleByTwo matcher will return the value if the value is divisible by 2.

In the preceding unit test code, we used beforeEach(), but Jasmine also provides afterEach(), for example, when we want to execute code after every Jasmine spec.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset