Introduction to Jasmine
Jasmine is a behavior-driven development (BDD) framework for testing JavaScript code. It does not rely on browsers, DOM, or any JavaScript framework. This makes it easy to test various types of JavaScript applications, regardless of how they’re built.
Getting Started
To get started with Jasmine, you can install it via npm:
npm install --save-dev jasmine
Setting Up Jasmine
To set up Jasmine, run:
npx jasmine init
This will generate a spec
directory and a support/jasmine.json
file where you can configure Jasmine.
Writing Tests in Jasmine
A Jasmine test suite begins with a describe
block. Inside this block, you can write individual tests using it
blocks. Here’s an example:
describe('Addition', function() { it('should add two numbers correctly', function() { expect(1 + 2).toBe(3); }); });
Matchers
Jasmine provides a rich set of matchers to assert the behavior of your application. Some commonly used matchers are:
toBe
: Check for strict equality.toEqual
: Check for deep equality.toBeTruthy
: Check if a value evaluates to true.toBeFalsy
: Check if a value evaluates to false.toContain
: Check if an array or string contains a specific value.toThrow
: Check if a function throws an exception.
Spies
Jasmine spies are a powerful way to create mock functions or objects. You can use them to track function calls and their parameters, and to manage dependencies. Here is an example:
describe('A spy', function() { it('tracks calls to a method', function() { var obj = { method: function() {} }; spyOn(obj, 'method'); obj.method(); expect(obj.method).toHaveBeenCalled(); expect(obj.method.calls.count()).toBe(1); }); });
Asynchronous Support
Jasmine provides support for testing asynchronous code using the done
function:
describe('Asynchronous tests', function() { it('waits for the async operation', function(done) { setTimeout(function() { expect(true).toBe(true); done(); }, 1000); }); });
An Application Example
Consider a simple JavaScript calculator application. Below is how you might test it using Jasmine:
// calculator.js function Calculator() { this.add = function(a, b) { return a + b; }; this.subtract = function(a, b) { return a - b; }; }
// calculatorSpec.js describe('Calculator', function() { var calculator; beforeEach(function() { calculator = new Calculator(); }); it('should add two numbers correctly', function() { expect(calculator.add(1, 2)).toBe(3); }); it('should subtract two numbers correctly', function() { expect(calculator.subtract(5, 2)).toBe(3); }); });
With this setup, you can confidently test the various functionalities of your calculator application.
Hash: 6d1c5859550824d403d8c31af9ac673b7ba206e6f87e61e096a017299f74d63f