This page is not available in every language. Missing translations are disabled in the language selector.

Quick reference

Jasmine BDD Testing Cheatsheet

A quick reference guide for Jasmine test framework: describe, it, matchers, spies, async testing, beforeEach/afterEach hooks, and HTML test runner.

· Published

Jasmine is a behavior-driven development framework for testing JavaScript code without external DOM dependencies.

Test Structure & BDD Syntax

describe('Calculator', () => {
  let calc;

  beforeEach(() => {
    calc = new Calculator();
  });

  afterEach(() => {
    calc.cleanup();
  });

  it('should add two numbers correctly', () => {
    expect(calc.add(2, 3)).toBe(5);
  });

  xit('temporarily skipped test', () => {
    // pending
  });
});

Matchers

expect(val).toBe(true);              // Strict equality (===)
expect(val).toEqual({ a: 1 });       // Deep object equality
expect(val).toMatch(/regex/);        // Regular expression match
expect(val).toBeDefined();           // Not undefined
expect(val).toBeUndefined();         // Is undefined
expect(val).toBeNull();              // Strict null
expect(val).toBeTruthy();            // Truthy coercion
expect(val).toBeFalsy();             // Falsy coercion
expect(arr).toContain('item');       // Array or string inclusion
expect(val).toBeLessThan(10);        // Numeric comparisons
expect(val).toBeGreaterThan(5);
expect(fn).toThrow();                // Exception thrown
expect(fn).toThrowError(TypeError);

Invert any matcher with .not:

expect(val).not.toBeNull();

Spies & Mock Functions

// Spy on an existing object method
spyOn(service, 'fetchData').and.returnValue(Promise.resolve([1, 2]));

service.fetchData('users');

expect(service.fetchData).toHaveBeenCalled();
expect(service.fetchData).toHaveBeenCalledWith('users');
expect(service.fetchData.calls.count()).toBe(1);

// Create standalone anonymous spy
const callback = jasmine.createSpy('myCallback');
callback('payload');
expect(callback).toHaveBeenCalledWith('payload');

Asynchronous Tests

it('fetches async data', async () => {
  const result = await fetchItems();
  expect(result.length).toBeGreaterThan(0);
});

References

Related topics