Jasmine Testing Framework: A Complete Guide to BDD Testing in JavaScript
Jasmine is one of the original JavaScript BDD testing frameworks. It shipped without dependencies long before Jest existed, influenced nearly every JS testing tool that came after it, and remains the default test runner for Angular projects. If you're working with Angular or want a battle-tested framework with a clean API, Jasmine is worth knowing well.
What Makes Jasmine Different
Jasmine is self-contained. Unlike Jest (which wraps Jasmine under the hood) or Mocha (which needs Chai for assertions), Jasmine ships with its own:
- Test runner
- Assertion library
- Spy/mock system
- HTML reporter
No configuration required to get started. No separate install for assertions. Just npm install jasmine and go.
Installation and Setup
Node.js (standalone):
npm install --save-dev jasmine
npx jasmine initThis creates:
spec/
support/
jasmine.jsonjasmine.json configures spec file patterns, helpers, and reporters:
{
"spec_dir": "spec",
"spec_files": ["**/*[sS]pec.js"],
"helpers": ["helpers/**/*.js"],
"stopSpecOnExpectationFailure": false,
"random": true
}Add to package.json:
{
"scripts": {
"test": "jasmine"
}
}Angular (built-in):
Angular CLI projects include Jasmine + Karma out of the box:
ng testThe Core Structure
Jasmine tests are organized with describe and it blocks:
describe('Calculator', () => {
describe('add()', () => {
it('adds two positive numbers', () => {
expect(add(2, 3)).toBe(5);
});
it('handles negative numbers', () => {
expect(add(-1, 1)).toBe(0);
});
it('handles zero', () => {
expect(add(0, 0)).toBe(0);
});
});
describe('divide()', () => {
it('divides correctly', () => {
expect(divide(10, 2)).toBe(5);
});
it('throws on division by zero', () => {
expect(() => divide(10, 0)).toThrow();
});
});
});describegroups related tests — nest as deep as neededit(ortest) defines a single test caseexpectchains to a matcher
Built-in Matchers
Jasmine's matcher library covers most scenarios without plugins:
// Equality
expect(value).toBe(42); // strict equality (===)
expect(obj).toEqual({a: 1}); // deep equality
expect(value).not.toBe(null); // negation
// Type checks
expect(value).toBeNull();
expect(value).toBeUndefined();
expect(value).toBeDefined();
expect(value).toBeTruthy();
expect(value).toBeFalsy();
// Numbers
expect(3.14).toBeCloseTo(3, 0);
expect(5).toBeGreaterThan(3);
expect(2).toBeLessThanOrEqual(2);
// Strings
expect('hello world').toContain('world');
expect('hello').toMatch(/^hell/);
// Arrays
expect([1, 2, 3]).toContain(2);
expect([]).toHaveSize(0);
// Objects
expect({a: 1, b: 2}).toEqual(jasmine.objectContaining({a: 1}));
// Errors
expect(() => riskyFunction()).toThrow();
expect(() => riskyFunction()).toThrowError('specific message');
expect(() => riskyFunction()).toThrowError(TypeError);Custom Matchers
Extend Jasmine with domain-specific assertions:
beforeEach(() => {
jasmine.addMatchers({
toBeWithinRange: () => ({
compare: (actual, floor, ceiling) => {
const pass = actual >= floor && actual <= ceiling;
return {
pass,
message: pass
? `Expected ${actual} not to be within [${floor}, ${ceiling}]`
: `Expected ${actual} to be within [${floor}, ${ceiling}]`
};
}
})
});
});
it('price is within expected range', () => {
expect(getPrice()).toBeWithinRange(10, 50);
});Setup and Teardown
Jasmine provides four lifecycle hooks:
describe('UserService', () => {
let service;
let db;
beforeAll(() => {
db = createTestDatabase();
});
afterAll(() => {
db.close();
});
beforeEach(() => {
service = new UserService(db);
});
afterEach(() => {
db.clear();
});
it('creates a user', () => {
const user = service.create({name: 'Alice'});
expect(user.id).toBeDefined();
});
});beforeAll/afterAllrun once perdescribeblockbeforeEach/afterEachrun around eachit- Hooks in nested
describeblocks apply only to that scope
Spies: Jasmine's Mock System
Spies are Jasmine's built-in approach to mocking. A spy wraps a function and records calls to it.
Spy on an existing method:
describe('EmailService', () => {
it('sends welcome email on registration', () => {
const mailer = { send: () => {} };
spyOn(mailer, 'send');
const service = new UserService(mailer);
service.register({email: 'alice@example.com'});
expect(mailer.send).toHaveBeenCalledOnceWith(
jasmine.objectContaining({ to: 'alice@example.com' })
);
});
});Control return values:
spyOn(api, 'fetchUser').and.returnValue({id: 1, name: 'Alice'});
spyOn(api, 'fetchUser').and.returnValues(first, second, third);
spyOn(api, 'fetchUser').and.throwError(new Error('Network error'));
spyOn(api, 'fetchUser').and.callFake((id) => ({ id, name: 'Fake' }));
spyOn(api, 'fetchUser').and.callThrough(); // calls original + recordsSpy call assertions:
expect(spy).toHaveBeenCalled();
expect(spy).toHaveBeenCalledTimes(3);
expect(spy).toHaveBeenCalledWith('arg1', 42);
expect(spy).toHaveBeenCalledOnceWith('arg1');
expect(spy).not.toHaveBeenCalled();
// Inspect individual calls
expect(spy.calls.count()).toBe(2);
expect(spy.calls.first().args).toEqual(['arg1']);
expect(spy.calls.mostRecent().returnValue).toBe(result);
spy.calls.reset(); // clear call historyCreate a standalone spy:
const callback = jasmine.createSpy('callback');
const obj = jasmine.createSpyObj('myObj', ['method1', 'method2']);Async Testing
Promises:
it('resolves user data', async () => {
const user = await fetchUser(1);
expect(user.name).toBe('Alice');
});
it('rejects with not found error', async () => {
await expectAsync(fetchUser(999)).toBeRejectedWith(
jasmine.objectContaining({ code: 'NOT_FOUND' })
);
});done callback (legacy style):
it('calls back with data', (done) => {
fetchUser(1, (err, user) => {
expect(err).toBeNull();
expect(user.name).toBe('Alice');
done();
});
});Observables (Angular):
import { of } from 'rxjs';
it('emits user data', (done) => {
const service = TestBed.inject(UserService);
spyOn(service, 'getUser').and.returnValue(of({ name: 'Alice' }));
service.getUser(1).subscribe(user => {
expect(user.name).toBe('Alice');
done();
});
});Jasmine Clock (fake timers):
describe('with fake timers', () => {
beforeEach(() => jasmine.clock().install());
afterEach(() => jasmine.clock().uninstall());
it('fires debounced function after delay', () => {
const handler = jasmine.createSpy('handler');
const debounced = debounce(handler, 500);
debounced();
expect(handler).not.toHaveBeenCalled();
jasmine.clock().tick(500);
expect(handler).toHaveBeenCalledOnce();
});
});Angular Component Testing
Jasmine + Angular TestBed is the standard Angular testing setup:
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { CounterComponent } from './counter.component';
describe('CounterComponent', () => {
let component: CounterComponent;
let fixture: ComponentFixture<CounterComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [CounterComponent]
}).compileComponents();
fixture = TestBed.createComponent(CounterComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('starts at zero', () => {
const el = fixture.debugElement.query(By.css('.count'));
expect(el.nativeElement.textContent).toBe('0');
});
it('increments on button click', () => {
const button = fixture.debugElement.query(By.css('button'));
button.triggerEventHandler('click', null);
fixture.detectChanges();
const el = fixture.debugElement.query(By.css('.count'));
expect(el.nativeElement.textContent).toBe('1');
});
});Focused and Excluded Tests
Skip individual tests during development:
// Run only this test
fit('only this runs', () => { ... });
fdescribe('only this suite runs', () => { ... });
// Skip these
xit('this is skipped', () => { ... });
xdescribe('this suite is skipped', () => { ... });Warning: Never commit fit/fdescribe — they silently skip all other tests in CI.
Running Tests
Basic run:
npx jasmine # all specs
npx jasmine spec/foo.js # single fileFilter by name:
npx jasmine --filter="Calculator"Random order:
npx jasmine --random=true --seed=12345With reporters:
Jasmine ships an HTML reporter for browser runs. For CI, use jasmine-spec-reporter:
npm install --save-dev jasmine-spec-reporter// spec/helpers/reporter.js
const { SpecReporter } = require('jasmine-spec-reporter');
jasmine.getEnv().clearReporters();
jasmine.getEnv().addReporter(
new SpecReporter({ spec: { displayPending: true } })
);Common Mistakes
Forgetting async/await:
// ❌ Wrong — test passes before the assertion runs
it('fetches data', () => {
fetchUser(1).then(user => {
expect(user.name).toBe('Alice');
});
});
// ✅ Correct
it('fetches data', async () => {
const user = await fetchUser(1);
expect(user.name).toBe('Alice');
});Sharing state between tests:
// ❌ Wrong — shared mutable state
let user = createUser();
it('test 1', () => { user.name = 'Modified'; });
it('test 2', () => { expect(user.name).toBe('Original'); }); // fails
// ✅ Correct — fresh state per test
let user;
beforeEach(() => { user = createUser(); });Spy not on object property:
// ❌ Wrong — can't spy on imported function directly
import { fetchUser } from './api';
spyOn(fetchUser); // won't work
// ✅ Correct — spy on the object method
import * as api from './api';
spyOn(api, 'fetchUser').and.returnValue(Promise.resolve(mockUser));Summary
Jasmine gives you a complete BDD testing toolkit with no dependencies. Its describe/it structure reads like requirements, spies make mocking straightforward, and async support covers callbacks, promises, and observables. It remains the bedrock of Angular testing and a solid choice for any JavaScript project that needs a self-contained, zero-configuration test framework.