Introducing Jasmine

Jasmine is an open source framework that is used to test JavaScript code without any dependency on DOM. As Angular is loosely coupled, we can use the Jasmine framework to test Angular components, services, and so on. Independent of each other, the clean syntax of Jasmine enables you to write tests very easily.

A global function named describe is the starting point of the Jasmine function. This global function takes a function and two parameters of type string. The string parameter describes the tests, and the function will have the actual implementation of testing:

describe("short description about the test suite", function() { 
}); 

The actual test methods are defined by a global function called the it function, which takes two arguments. The first argument is the title of the test or spec, and the second argument is the function that tests the expectations by verifying the state of the code. Expectations are similar to assert in the Microsoft unit test framework. If any one of the defined expectations fails in the spec, it is called the failing spec. The following code illustrates the preceding statements:

describe("short description about the test suite", function() { 
  it("a spec with single expectation", function() { 
    expect(true).toBe(true); 
  }); 
}); 

The test or spec method will have one or more expect statements, as illustrated, that compare the actual value with the expected value using the matcher functions that are chained to the expect function; various default matcher functions are available:

describe("short description about the test suite", function() { 
it("a spec with single expectation", function() { 
expect(afunction).toThrow(e); 
expect(true).toBe(true); 
expect(variable).toBeDefined(); 
expect(variable).toBeFalsy(); 
expect(number).toBeGreaterThan(number); 
expect(number).toBeLessThan(number); 
expect(variable).toBeNull(); 
expect(variable).toBeTruthy(); 
expect(value).toBeUndefined(); 
expect(array).toContain(member); 
expect(string).toContain(substring); 
expect(variable).toEqual(variable); 
expect(value).toMatch(pattern); 
  }); 
}); 

We have only seen the basics of the Jasmine framework, and there are more features available. You can learn about them by visiting the official website at http://jasmine.github.io/. This introduction is enough for us to learn to test Angular services and components.

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

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