Jasmine Spies and Mocking: Advanced Patterns for JavaScript Testing
Jasmine's spy system is more powerful than most developers use. The basics — spyOn, toHaveBeenCalled, returnValue — cover a lot of ground, but the advanced patterns let you isolate complex dependencies, simulate time, and test asynchronous workflows reliably. This guide covers the full spy API and practical mocking patterns.
How Spies Work Under the Hood
When you call spyOn(obj, 'method'), Jasmine replaces obj.method with a proxy function that:
- Records every call (arguments, return value, this context)
- Does NOT call the original implementation by default
- Returns
undefinedunless you configure a return value
The original function is stored internally and can be restored with .and.callThrough() or at the end of the spec.
const calculator = {
add: (a, b) => a + b
};
spyOn(calculator, 'add');
// Original is gone during this test
calculator.add(2, 3); // returns undefined
expect(calculator.add).toHaveBeenCalledWith(2, 3);Jasmine automatically restores all spies after each spec — you don't need teardown code.
The Full .and API
.and.returnValue(val)
Return the same value every time:
spyOn(userRepo, 'findById').and.returnValue({ id: 1, name: 'Alice' });
const user = userService.getUser(1);
expect(user.name).toBe('Alice');.and.returnValues(v1, v2, v3)
Return different values on successive calls:
spyOn(dice, 'roll').and.returnValues(6, 1, 3);
expect(dice.roll()).toBe(6);
expect(dice.roll()).toBe(1);
expect(dice.roll()).toBe(3);
expect(dice.roll()).toBeUndefined(); // exhaustedUseful for testing retry logic, pagination, or any stateful sequence.
.and.resolveTo(val) / .and.rejectWith(err)
For async spies on Promise-returning methods:
spyOn(api, 'fetchUser').and.resolveTo({ id: 1, name: 'Alice' });
spyOn(api, 'deleteUser').and.rejectWith(new Error('Forbidden'));
// In tests
const user = await userService.getUser(1);
expect(user.name).toBe('Alice');
await expectAsync(userService.deleteUser(1)).toBeRejectedWithError('Forbidden');.and.callFake(fn)
Replace with a custom function for complex behavior:
spyOn(cache, 'get').and.callFake((key) => {
const store = { 'user:1': { name: 'Alice' }, 'user:2': { name: 'Bob' } };
return store[key] ?? null;
});
expect(cache.get('user:1')).toEqual({ name: 'Alice' });
expect(cache.get('user:99')).toBeNull();Use callFake when return values depend on arguments or need complex logic.
.and.callThrough()
Call the original implementation AND record the call:
spyOn(logger, 'warn').and.callThrough();
// Real code runs, but we can assert it was called
service.processInvalidInput('bad data');
expect(logger.warn).toHaveBeenCalledWith(jasmine.stringContaining('bad data'));Useful when you want to verify a method was called without changing its behavior.
.and.throwError(err)
Simulate failures:
spyOn(db, 'query').and.throwError(new Error('Connection timeout'));
expect(() => service.loadUsers()).toThrowError('Connection timeout');Inspecting Call History
The calls object gives you full access to every call:
const spy = spyOn(eventBus, 'emit');
service.processOrder(order);
// Count
expect(spy.calls.count()).toBe(3);
// Check if ever called
expect(spy.calls.any()).toBeTrue();
// First call
const firstCall = spy.calls.first();
expect(firstCall.args).toEqual(['order:created', jasmine.objectContaining({ id: order.id })]);
expect(firstCall.returnValue).toBeUndefined();
expect(firstCall.object).toBe(eventBus);
// Most recent call
const lastCall = spy.calls.mostRecent();
expect(lastCall.args[0]).toBe('order:fulfilled');
// All calls as array
const allCalls = spy.calls.all();
const eventNames = allCalls.map(call => call.args[0]);
expect(eventNames).toEqual(['order:created', 'payment:processed', 'order:fulfilled']);
// Reset for next assertion
spy.calls.reset();
expect(spy.calls.count()).toBe(0);Spy Matchers Reference
// Called at all
expect(spy).toHaveBeenCalled();
expect(spy).not.toHaveBeenCalled();
// Called exactly N times
expect(spy).toHaveBeenCalledTimes(3);
// Called with specific args (any call)
expect(spy).toHaveBeenCalledWith('arg1', jasmine.any(Number));
// Called exactly once with specific args
expect(spy).toHaveBeenCalledOnceWith('arg1', 42);
// Partial arg matching
expect(spy).toHaveBeenCalledWith(
jasmine.objectContaining({ id: 1 }),
jasmine.arrayContaining([2, 3])
);Asymmetric Matchers for Partial Matching
When exact equality is too strict:
jasmine.any(Type) // any instance of Type
jasmine.anything() // anything except null/undefined
jasmine.objectContaining({key: val}) // object with at least these keys
jasmine.arrayContaining([1, 2]) // array with at least these elements
jasmine.stringContaining('substr') // string with substring
jasmine.stringMatching(/regex/) // string matching pattern
jasmine.truthy() // any truthy value
jasmine.falsy() // any falsy valueReal usage:
expect(mailer.send).toHaveBeenCalledWith(
jasmine.objectContaining({
to: 'user@example.com',
subject: jasmine.stringContaining('Welcome')
})
);createSpyObj: Full Object Mocks
When you need to mock an entire dependency:
describe('CheckoutService', () => {
let paymentGateway;
let inventoryService;
let service;
beforeEach(() => {
paymentGateway = jasmine.createSpyObj('PaymentGateway', {
charge: Promise.resolve({ transactionId: 'txn_123' }),
refund: Promise.resolve({ refunded: true })
});
inventoryService = jasmine.createSpyObj('InventoryService', ['reserve', 'release']);
inventoryService.reserve.and.returnValue(true);
service = new CheckoutService(paymentGateway, inventoryService);
});
it('charges payment and reserves inventory', async () => {
await service.checkout({ items: ['item-1'], total: 99 });
expect(inventoryService.reserve).toHaveBeenCalledWith(['item-1']);
expect(paymentGateway.charge).toHaveBeenCalledWith(99);
});
it('releases inventory if payment fails', async () => {
paymentGateway.charge.and.rejectWith(new Error('Card declined'));
await expectAsync(service.checkout({ items: ['item-1'], total: 99 }))
.toBeRejectedWithError('Card declined');
expect(inventoryService.release).toHaveBeenCalledWith(['item-1']);
});
});createSpyObj signature:
// Methods as array (return undefined by default)
jasmine.createSpyObj('name', ['method1', 'method2']);
// Methods as object with default return values
jasmine.createSpyObj('name', {
method1: returnValue1,
method2: returnValue2
});
// With properties
jasmine.createSpyObj('name', ['method1'], { property1: 'value' });Standalone Spies
Create a spy without attaching it to an object:
it('calls callback with processed result', () => {
const onSuccess = jasmine.createSpy('onSuccess');
const onError = jasmine.createSpy('onError');
processor.run(data, { onSuccess, onError });
expect(onSuccess).toHaveBeenCalledOnceWith({ processed: true });
expect(onError).not.toHaveBeenCalled();
});Useful for testing callbacks, event handlers, and constructor arguments.
Clock Manipulation
Control time for testing time-dependent code:
describe('Debounce and Timeout', () => {
beforeEach(() => {
jasmine.clock().install();
});
afterEach(() => {
jasmine.clock().uninstall();
});
it('debounces rapid calls', () => {
const handler = jasmine.createSpy('handler');
const debounced = debounce(handler, 300);
debounced('a');
debounced('b');
debounced('c');
expect(handler).not.toHaveBeenCalled();
jasmine.clock().tick(300);
expect(handler).toHaveBeenCalledOnceWith('c');
});
it('retries after timeout', () => {
const apiCall = jasmine.createSpy('apiCall').and.callFake(() => {
throw new Error('timeout');
});
service.fetchWithRetry(apiCall, { retryDelay: 1000, maxRetries: 3 });
expect(apiCall).toHaveBeenCalledTimes(1);
jasmine.clock().tick(1000);
expect(apiCall).toHaveBeenCalledTimes(2);
jasmine.clock().tick(1000);
expect(apiCall).toHaveBeenCalledTimes(3);
});
it('works with fixed Date', () => {
const baseTime = new Date(2024, 0, 15, 12, 0, 0);
jasmine.clock().mockDate(baseTime);
expect(new Date().toISOString()).toContain('2024-01-15');
jasmine.clock().tick(60000); // 1 minute
expect(new Date().toISOString()).toContain('12:01');
});
});HTTP Mocking with jasmine-ajax
For browser environments, jasmine-ajax intercepts XHR calls:
npm install --save-dev jasmine-ajaxdescribe('API client', () => {
beforeEach(() => {
jasmine.Ajax.install();
});
afterEach(() => {
jasmine.Ajax.uninstall();
});
it('parses user response correctly', (done) => {
const client = new ApiClient();
client.getUser(1).then(user => {
expect(user.name).toBe('Alice');
done();
});
const request = jasmine.Ajax.requests.mostRecent();
expect(request.url).toBe('/api/users/1');
expect(request.method).toBe('GET');
request.respondWith({
status: 200,
responseText: JSON.stringify({ id: 1, name: 'Alice' })
});
});
it('handles network errors', (done) => {
client.getUser(1).catch(err => {
expect(err.message).toContain('Network error');
done();
});
jasmine.Ajax.requests.mostRecent().responseError();
});
});Dependency Injection Pattern for Testability
The key to effective mocking is designing code that accepts its dependencies:
// ❌ Hard to test — creates own dependencies
class OrderService {
constructor() {
this.db = new Database(); // can't replace
this.mailer = new Mailer(); // can't replace
}
}
// ✅ Easy to test — dependencies injected
class OrderService {
constructor(db, mailer) {
this.db = db;
this.mailer = mailer;
}
}
// In production
const service = new OrderService(new Database(), new Mailer());
// In tests
const db = jasmine.createSpyObj('db', ['findOrder', 'saveOrder']);
const mailer = jasmine.createSpyObj('mailer', ['send']);
const service = new OrderService(db, mailer);Spying on Getters and Setters
const config = { get debug() { return false; } };
// Spy on getter
const spy = spyOnProperty(config, 'debug', 'get').and.returnValue(true);
expect(config.debug).toBe(true);
expect(spy).toHaveBeenCalled();
// Spy on setter
const setSpy = spyOnProperty(config, 'debug', 'set');
config.debug = false;
expect(setSpy).toHaveBeenCalledWith(false);Common Pitfalls
Forgetting and.callThrough() breaks real behavior:
If you spy on a method without configuring it, the original code stops running. This causes confusing failures when other tests depend on side effects of that method.
Spying on ES module imports:
// ❌ This doesn't work with ES modules
import { fetchUser } from './api.js';
spyOn(fetchUser);
// ✅ Use namespace import or dependency injection
import * as api from './api.js';
spyOn(api, 'fetchUser');Not resetting spies with calls.reset() when reusing across tests:
Use beforeEach to re-spy rather than trying to reset manually — Jasmine restores spies between specs automatically.
Asserting too early with async:
// ❌ Assertion runs before promise resolves
it('loads data', () => {
service.load();
expect(spy).toHaveBeenCalled(); // might be false
});
// ✅ Await the operation
it('loads data', async () => {
await service.load();
expect(spy).toHaveBeenCalled();
});Summary
Jasmine's spy system gives you precise control over dependencies:
spyOnwraps existing methods;createSpy/createSpyObjbuild mocks from scratch.and.returnValue,.and.callFake,.and.resolveTocontrol behaviorcalls.all(),calls.first(),calls.mostRecent()give full call historyjasmine.clock()controls time without touching production code- Asymmetric matchers like
objectContainingmake assertions flexible without being loose
The goal is tests that are specific about what matters and flexible about what doesn't. A well-placed spy gives you confidence a dependency was used correctly without making tests fragile to unrelated implementation changes.