Jasmine Unit Testing: Writing Fast, Reliable Tests for JavaScript
Unit testing with Jasmine gives you a clean, readable syntax for verifying that individual functions do exactly what they're supposed to do — nothing more. This guide covers how to write Jasmine unit tests that are fast, reliable, and actually useful.
What Jasmine Unit Testing Looks Like
A Jasmine unit test follows a straightforward structure: describe the unit you're testing, write it blocks for each behavior, and use expect with a matcher to assert the result.
describe('calculateDiscount', () => {
it('applies percentage discount to price', () => {
const result = calculateDiscount(100, 20);
expect(result).toBe(80);
});
it('returns full price when discount is zero', () => {
const result = calculateDiscount(100, 0);
expect(result).toBe(100);
});
it('throws for negative discount', () => {
expect(() => calculateDiscount(100, -5)).toThrow();
});
});This is the entire pattern. The challenge is not learning the API — it's writing tests that fail for the right reasons and pass for the right reasons.
Installing Jasmine for Unit Testing
npm install --save-dev jasmine
npx jasmine initThis creates spec/support/jasmine.json with default configuration:
{
"spec_dir": "spec",
"spec_files": ["**/*[sS]pec.js"],
"helpers": ["helpers/**/*.js"],
"stopSpecOnExpectationFailure": false,
"random": true
}Add a test script to package.json:
{
"scripts": {
"test": "jasmine",
"test:watch": "jasmine --watch"
}
}Core Matchers for Unit Testing
Jasmine ships with matchers that cover most unit testing scenarios:
Equality Matchers
// Strict equality (===)
expect(value).toBe(42);
expect(result).not.toBe(null);
// Deep equality (objects and arrays)
expect(user).toEqual({ id: 1, name: 'Alice' });
expect(tags).toEqual(['js', 'testing']);
// Partial object matching
expect(response).toEqual(jasmine.objectContaining({
status: 200
}));Type and Value Matchers
expect(result).toBeDefined();
expect(cache).toBeUndefined();
expect(response).toBeNull();
expect(flag).toBeTruthy();
expect(errors).toBeFalsy();
expect(price).toBeGreaterThan(0);
expect(count).toBeLessThanOrEqual(100);
expect(ratio).toBeCloseTo(0.333, 2);String and Array Matchers
expect(message).toContain('success');
expect(tags).toContain('javascript');
expect(slug).toMatch(/^[a-z0-9-]+$/);
expect(items).toHaveSize(3);Error Matchers
expect(() => parseJSON('{bad}')).toThrow();
expect(() => validateAge(-1)).toThrowError('Age must be positive');
expect(() => divide(1, 0)).toThrowError(RangeError);Structuring Unit Tests Effectively
One Describe Block Per Unit
Map each unit (function, class, module) to one describe block:
describe('UserValidator', () => {
describe('validateEmail', () => {
it('accepts valid email addresses', () => {
expect(UserValidator.validateEmail('user@example.com')).toBe(true);
});
it('rejects missing @ symbol', () => {
expect(UserValidator.validateEmail('notanemail')).toBe(false);
});
it('rejects empty string', () => {
expect(UserValidator.validateEmail('')).toBe(false);
});
});
describe('validatePassword', () => {
it('requires minimum 8 characters', () => {
expect(UserValidator.validatePassword('short')).toBe(false);
});
it('accepts strong passwords', () => {
expect(UserValidator.validatePassword('S3cur3Pass!')).toBe(true);
});
});
});Setup and Teardown
Use beforeEach and afterEach to avoid repeating setup code:
describe('ShoppingCart', () => {
let cart;
beforeEach(() => {
cart = new ShoppingCart();
});
afterEach(() => {
cart.clear();
});
it('starts empty', () => {
expect(cart.items).toHaveSize(0);
expect(cart.total).toBe(0);
});
it('adds items correctly', () => {
cart.add({ id: 1, price: 29.99, quantity: 2 });
expect(cart.items).toHaveSize(1);
expect(cart.total).toBe(59.98);
});
it('removes items by id', () => {
cart.add({ id: 1, price: 10 });
cart.add({ id: 2, price: 20 });
cart.remove(1);
expect(cart.items).toHaveSize(1);
expect(cart.total).toBe(20);
});
});For expensive setup that runs once per suite, use beforeAll:
describe('DatabaseQuery', () => {
let db;
beforeAll(async () => {
db = await createTestDatabase();
await db.seed(testData);
});
afterAll(async () => {
await db.destroy();
});
it('finds users by email', async () => {
const user = await db.users.findByEmail('test@example.com');
expect(user).toBeDefined();
});
});Testing Pure Functions
Pure functions are the easiest things to unit test — same input always produces the same output:
// Function under test
function formatCurrency(amount, currency = 'USD') {
if (typeof amount !== 'number') throw new TypeError('Amount must be a number');
if (amount < 0) throw new RangeError('Amount cannot be negative');
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency
}).format(amount);
}
// Tests
describe('formatCurrency', () => {
it('formats USD amounts', () => {
expect(formatCurrency(1234.56)).toBe('$1,234.56');
});
it('formats other currencies', () => {
expect(formatCurrency(1000, 'EUR')).toBe('€1,000.00');
});
it('handles zero', () => {
expect(formatCurrency(0)).toBe('$0.00');
});
it('throws for non-numeric input', () => {
expect(() => formatCurrency('abc')).toThrowError(TypeError);
});
it('throws for negative amounts', () => {
expect(() => formatCurrency(-10)).toThrowError(RangeError);
});
});Testing Classes and Objects
class EventEmitter {
constructor() {
this.listeners = {};
}
on(event, callback) {
if (!this.listeners[event]) {
this.listeners[event] = [];
}
this.listeners[event].push(callback);
return this;
}
emit(event, data) {
const callbacks = this.listeners[event] || [];
callbacks.forEach(cb => cb(data));
return this;
}
off(event, callback) {
if (this.listeners[event]) {
this.listeners[event] = this.listeners[event].filter(cb => cb !== callback);
}
return this;
}
}
// Tests
describe('EventEmitter', () => {
let emitter;
beforeEach(() => {
emitter = new EventEmitter();
});
it('calls registered listeners when event fires', () => {
const spy = jasmine.createSpy('listener');
emitter.on('data', spy);
emitter.emit('data', { value: 42 });
expect(spy).toHaveBeenCalledWith({ value: 42 });
});
it('calls multiple listeners for same event', () => {
const spy1 = jasmine.createSpy('listener1');
const spy2 = jasmine.createSpy('listener2');
emitter.on('event', spy1).on('event', spy2);
emitter.emit('event');
expect(spy1).toHaveBeenCalled();
expect(spy2).toHaveBeenCalled();
});
it('does not call removed listeners', () => {
const spy = jasmine.createSpy('listener');
emitter.on('event', spy);
emitter.off('event', spy);
emitter.emit('event');
expect(spy).not.toHaveBeenCalled();
});
it('does nothing when emitting event with no listeners', () => {
expect(() => emitter.emit('unknown')).not.toThrow();
});
});Testing with Spies
Spies replace functions with tracked versions, letting you verify calls without executing real code:
describe('NotificationService', () => {
let service;
let emailSpy;
beforeEach(() => {
emailSpy = jasmine.createSpy('sendEmail').and.returnValue(Promise.resolve());
service = new NotificationService({ send: emailSpy });
});
it('sends welcome email on user registration', async () => {
await service.registerUser({ email: 'user@example.com', name: 'Alice' });
expect(emailSpy).toHaveBeenCalledOnce();
expect(emailSpy).toHaveBeenCalledWith(
jasmine.objectContaining({
to: 'user@example.com',
subject: jasmine.stringContaining('Welcome')
})
);
});
it('does not send email when user already exists', async () => {
await service.registerUser({ email: 'existing@example.com' });
expect(emailSpy).not.toHaveBeenCalled();
});
});Testing Async Code
Promises
describe('fetchUserData', () => {
it('resolves with user data for valid id', async () => {
const user = await fetchUserData(1);
expect(user).toEqual(jasmine.objectContaining({ id: 1 }));
});
it('rejects for invalid id', async () => {
await expectAsync(fetchUserData(-1)).toBeRejectedWithError('User not found');
});
});Observable Streams (with done callback)
describe('DataStream', () => {
it('emits values in sequence', (done) => {
const results = [];
const stream = new DataStream([1, 2, 3]);
stream.subscribe({
next: (val) => results.push(val),
complete: () => {
expect(results).toEqual([1, 2, 3]);
done();
}
});
});
});Using Custom Matchers
When built-in matchers aren't expressive enough, write your own:
const validationMatchers = {
toBeValidEmail: function() {
return {
compare: function(actual) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const pass = emailRegex.test(actual);
return {
pass,
message: pass
? `Expected ${actual} not to be a valid email`
: `Expected ${actual} to be a valid email`
};
}
};
}
};
describe('Email validation', () => {
beforeEach(() => {
jasmine.addMatchers(validationMatchers);
});
it('validates email format', () => {
expect('user@example.com').toBeValidEmail();
expect('notanemail').not.toBeValidEmail();
});
});Parameterized Tests
Jasmine doesn't have a built-in test.each like Jest, but you can achieve the same with loops:
describe('isPrime', () => {
const primes = [2, 3, 5, 7, 11, 13, 17, 19];
const nonPrimes = [0, 1, 4, 6, 8, 9, 10, 12];
primes.forEach(n => {
it(`returns true for prime number ${n}`, () => {
expect(isPrime(n)).toBe(true);
});
});
nonPrimes.forEach(n => {
it(`returns false for non-prime ${n}`, () => {
expect(isPrime(n)).toBe(false);
});
});
});Common Unit Testing Mistakes
Testing implementation, not behavior: Don't assert that a private method was called — assert the observable outcome.
// Bad: tests implementation detail
expect(cart._recalculate).toHaveBeenCalled();
// Good: tests observable outcome
expect(cart.total).toBe(59.98);Too broad test descriptions: "it works" tells you nothing when it fails.
// Bad
it('works correctly', () => { ... });
// Good
it('reduces total when discount code is applied', () => { ... });Multiple assertions without isolation: If one assert fails, you lose visibility into the others.
// Better: one clear assertion per test
it('returns 200 status', () => {
expect(response.status).toBe(200);
});
it('returns user object in body', () => {
expect(response.body).toEqual(jasmine.objectContaining({ id: 1 }));
});Running Jasmine Unit Tests
# Run all tests
npm test
# Run specific spec file
npx jasmine spec/cart.spec.js
# Run tests matching a pattern
npx jasmine --filter="ShoppingCart"
# Run with verbose output
npx jasmine --reporter=verboseIntegrating with HelpMeTest
Jasmine unit tests cover functions in isolation. But isolating a function doesn't prove the application works end-to-end. HelpMeTest complements Jasmine by testing real user flows in a real browser — no code required.
You write plain English: "user adds item to cart, checks out, sees order confirmation." HelpMeTest runs it against your live application on a schedule, catches regressions before users do, and alerts you when something breaks.
Usage-based pricing ($0.003/test run) includes 24/7 monitoring. Start testing.
Summary
Jasmine unit testing gives you a readable syntax, a full set of matchers, and enough flexibility to test anything from pure functions to complex async flows. Set up is minimal, the API is stable, and tests run fast.
The key is writing tests for behavior — what a function should do — not for implementation details. Tests written this way survive refactors and catch real bugs.