Brief introduction to Jasmine

Jasmine is a JavaScript testing framework with zero dependencies. With npm, you can install it as follows:

npm install jasmine-core --save-dev

You also need to install the Jasmine type definition file. Otherwise, the TypeScript compiler will not know about the Jasmine types.

npm install @types/jasmine --save-dev

Jasmine has four main concepts:

  • Specs: In Jasmine terminology, unit tests are called specs. The it(string, function) function specifies a test. It takes a title and a function containing one or more expectations.
  • Suites: Specs are wrapped in suites. The describe(string, function) function describes a test suite. It takes a title and a function containing one or more specs. Suit can contain other nested suites as well.
  • Expectations: These are assertions which are specified using the expect(actual) function. The function gets one argument--the actual value.
  • Matchers: Assertions are followed by matchers. Jasmine has a lot of matchers such as toBe(expected), toEqual(expected), toBeLessThan(expected), and many more. The expected argument is the expected value. For example, expect(2 + 3).toBeLessThan(6). Matchers implement a Boolean comparison between actual and expected values. If the matcher returns true, the spec passes; otherwise, an error is thrown. Any matcher can be negated with not; for example, expect(array).not.toContain(member).
A full list of matchers is available on GitHub at https://github.com/JamieMason/Jasmine-Matchers.

An example of a simple test with Jasmine is shown here:

describe("Test matchers:", function() {
it("Compare two values with 'toBe' matcher", function() {
var a = 5;
var b = 2 + 3;

expect(a).toBe(b);
expect(a).not.toBe(null);
});
});
The titles in the functions it() and describe() serve the purpose of documentation. Tests should be self-described so that other developers can better understand what the test does.

Jasmine has some setup and teardown functions:

  • beforeAll(): Executes some code before the suite runs.
  • beforeEach(): Executes some code before each spec runs.
  • afterAll(): Executes some code after the suite is finished.
  • afterEach(): Executes some code after each spec is finished.

An example with beforeEach() and afterAll() is demonstrated here:

describe("Usage of beforeEach and afterAll", function() {
var foo = 0;

beforeEach(function() {
foo += 1;
});

afterAll(function() {
foo = 0;
});

it("Check if foo == 1", function() {
expect(foo).toEqual(1);
});

it("Check if foo == 2", function() {
expect(foo).toEqual(2);
});
});
..................Content has been hidden....................

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