Jasmine Async Testing: Promises, Observables, and Done Callbacks

Jasmine Async Testing: Promises, Observables, and Done Callbacks

Async code is where JavaScript tests get painful. Callbacks, promises, observables — each requires a different approach. Jasmine handles all of them, but you need to tell Jasmine to wait for your async operations to finish. This guide covers every async pattern you'll encounter.

Why Async Testing is Different

A synchronous test completes when the last line runs. Jasmine knows it's done:

it('adds two numbers', () => {
  expect(1 + 1).toBe(2);
  // Jasmine: test complete
});

An async test starts an operation that completes later. If Jasmine doesn't wait, the test finishes before your assertion runs — and it always passes, even when it should fail:

// BROKEN: always passes, never actually tests anything
it('loads user data', () => {
  fetchUser(1).then(user => {
    expect(user.id).toBe(1); // runs after Jasmine marks test as done
  });
});

Every async test must give Jasmine a way to know when to check results.

Method 1: The done Callback

The oldest pattern. Jasmine passes a done function to your test — call it when the async work completes:

it('fetches user by id', (done) => {
  fetchUser(1).then(user => {
    expect(user.id).toBe(1);
    expect(user.name).toBeDefined();
    done(); // tell Jasmine we're finished
  }).catch(err => {
    done.fail(err); // tell Jasmine the test failed
  });
});

Always call done.fail(err) in the catch block, otherwise a rejected promise just silently hangs until timeout.

Callback-Based Code

The done pattern also works for old-school Node.js callbacks:

it('reads file contents', (done) => {
  fs.readFile('./config.json', 'utf8', (err, data) => {
    if (err) {
      done.fail(err);
      return;
    }
    expect(JSON.parse(data)).toBeDefined();
    done();
  });
});

Default Timeout

Jasmine waits 5 seconds by default. If done isn't called in time, the test fails with a timeout error. Adjust this globally or per test:

// Globally (in jasmine.json or spec helper)
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;

// Per test
it('slow operation', (done) => {
  // ...
}, 15000); // 15 second timeout for this test

Method 2: Returning a Promise

Cleaner than done for promise-based code. Jasmine detects that you returned a promise and waits for it to resolve or reject:

it('creates a user', () => {
  return UserService.create({ name: 'Alice', email: 'alice@example.com' })
    .then(user => {
      expect(user.id).toBeDefined();
      expect(user.name).toBe('Alice');
    });
});

If the promise rejects, Jasmine marks the test as failed with the rejection reason.

Testing Rejected Promises

it('rejects when email already exists', () => {
  return expectAsync(
    UserService.create({ email: 'existing@example.com' })
  ).toBeRejectedWith(jasmine.objectContaining({ code: 'EMAIL_EXISTS' }));
});

Method 3: async/await

The cleanest approach. Use async/await and Jasmine handles the rest:

it('updates user profile', async () => {
  const user = await UserService.findById(1);
  const updated = await UserService.update(user.id, { name: 'Bob' });

  expect(updated.name).toBe('Bob');
  expect(updated.updatedAt).toBeGreaterThan(user.updatedAt);
});

For error assertions:

it('throws when user not found', async () => {
  await expectAsync(UserService.findById(9999)).toBeRejectedWithError('User not found');
});

// Or with try/catch
it('throws for invalid input', async () => {
  try {
    await UserService.create({ name: '' });
    fail('Expected an error to be thrown');
  } catch (err) {
    expect(err.message).toContain('Name is required');
  }
});

The expectAsync API

Jasmine 3+ includes expectAsync for asserting on promise outcomes without unwrapping:

// Assert promise resolves
await expectAsync(fetchData()).toBeResolved();

// Assert promise resolves with specific value
await expectAsync(fetchUser(1)).toBeResolvedTo({ id: 1, name: 'Alice' });

// Assert promise rejects
await expectAsync(fetchUser(-1)).toBeRejected();

// Assert promise rejects with error
await expectAsync(fetchUser(-1)).toBeRejectedWithError('User not found');
await expectAsync(fetchUser(-1)).toBeRejectedWithError(Error, 'User not found');

// Negate
await expectAsync(sendEmail(to)).not.toBeRejected();

Note: you must await the expectAsync call itself, otherwise the assertion runs asynchronously and may not execute.

Testing RxJS Observables

RxJS is common in Angular codebases. Testing observables requires collecting emissions and waiting for the stream to complete.

Simple Observable Test

import { of } from 'rxjs';
import { map } from 'rxjs/operators';

it('transforms values in stream', (done) => {
  const values = [];

  of(1, 2, 3).pipe(
    map(x => x * 2)
  ).subscribe({
    next: (val) => values.push(val),
    complete: () => {
      expect(values).toEqual([2, 4, 6]);
      done();
    },
    error: done.fail
  });
});

Testing HttpClient in Angular

Angular's HttpClientTestingModule integrates with Jasmine:

import { TestBed } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';

describe('ApiService', () => {
  let service: ApiService;
  let httpMock: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [ApiService]
    });
    service = TestBed.inject(ApiService);
    httpMock = TestBed.inject(HttpTestingController);
  });

  afterEach(() => {
    httpMock.verify(); // ensures no unexpected requests
  });

  it('fetches users from API', () => {
    const mockUsers = [{ id: 1, name: 'Alice' }];

    service.getUsers().subscribe(users => {
      expect(users).toEqual(mockUsers);
    });

    const req = httpMock.expectOne('/api/users');
    expect(req.request.method).toBe('GET');
    req.flush(mockUsers);
  });
});

Using TestScheduler for Time-Based Observables

import { TestScheduler } from 'rxjs/testing';

describe('debounceSearch', () => {
  let scheduler: TestScheduler;

  beforeEach(() => {
    scheduler = new TestScheduler((actual, expected) => {
      expect(actual).toEqual(expected);
    });
  });

  it('debounces input by 300ms', () => {
    scheduler.run(({ cold, expectObservable }) => {
      const input =  cold('a-b-c---d|');
      const expected =    '------c---d|';

      const result = debounceSearch(input, scheduler);
      expectObservable(result).toBe(expected);
    });
  });
});

Fake Timers

Testing code with setTimeout, setInterval, or Date.now() is painful without fake timers. Jasmine provides a clock API:

describe('RetryManager', () => {
  beforeEach(() => {
    jasmine.clock().install();
  });

  afterEach(() => {
    jasmine.clock().uninstall(); // always uninstall or other tests break
  });

  it('retries after delay', () => {
    const mockFn = jasmine.createSpy('operation').and.returnValues(
      Promise.reject(new Error('fail')),
      Promise.resolve('success')
    );

    const manager = new RetryManager(mockFn, { delay: 1000 });
    manager.start();

    expect(mockFn).toHaveBeenCalledTimes(1);

    jasmine.clock().tick(1000); // advance time by 1 second

    expect(mockFn).toHaveBeenCalledTimes(2);
  });

  it('limits to max retries', () => {
    const mockFn = jasmine.createSpy('operation').and.rejectWith(new Error('always fails'));
    const manager = new RetryManager(mockFn, { delay: 500, maxRetries: 3 });

    manager.start();

    jasmine.clock().tick(500);
    jasmine.clock().tick(500);
    jasmine.clock().tick(500);

    expect(mockFn).toHaveBeenCalledTimes(4); // initial + 3 retries
  });
});

Mocking Date.now()

it('generates timestamp-based ids', () => {
  jasmine.clock().mockDate(new Date('2026-01-15T10:00:00Z'));

  const id = generateId();
  expect(id).toContain('20260115');
});

Common Async Testing Mistakes

Forgetting to Return or Await

// WRONG: Jasmine doesn't wait for this promise
it('creates user', () => {
  UserService.create({ name: 'Alice' }).then(user => {
    expect(user.name).toBe('Alice');
  });
  // test finishes here, expect never runs
});

// RIGHT: return the promise
it('creates user', () => {
  return UserService.create({ name: 'Alice' }).then(user => {
    expect(user.name).toBe('Alice');
  });
});

// RIGHT: use async/await
it('creates user', async () => {
  const user = await UserService.create({ name: 'Alice' });
  expect(user.name).toBe('Alice');
});

Not Calling done.fail on Errors

// WRONG: rejected promise causes timeout, not failure
it('fetches data', (done) => {
  fetchData().then(data => {
    expect(data).toBeDefined();
    done();
  });
  // if fetchData() rejects, done() never called = timeout
});

// RIGHT: always handle errors
it('fetches data', (done) => {
  fetchData()
    .then(data => {
      expect(data).toBeDefined();
      done();
    })
    .catch(done.fail);
});

Forgetting to Uninstall the Clock

// If you install jasmine.clock() without uninstalling it,
// time is frozen for ALL subsequent tests in the suite.
// Always pair install() with afterEach uninstall().

beforeEach(() => jasmine.clock().install());
afterEach(() => jasmine.clock().uninstall()); // required

Mixing done with async

// WRONG: using done with async function
it('test', async (done) => {
  const result = await fetchData();
  expect(result).toBeDefined();
  done(); // unnecessary and can cause double-resolution warnings
});

// RIGHT: async without done
it('test', async () => {
  const result = await fetchData();
  expect(result).toBeDefined();
});

Testing Multiple Async Calls

describe('Dashboard', () => {
  it('loads all required data in parallel', async () => {
    const [user, orders, notifications] = await Promise.all([
      fetchUser(1),
      fetchOrders(1),
      fetchNotifications(1)
    ]);

    expect(user).toBeDefined();
    expect(orders).toBeInstanceOf(Array);
    expect(notifications).toBeInstanceOf(Array);
  });
});

Summary

Scenario Use
Callbacks done callback
Promises Return the promise or async/await
Assert rejection expectAsync().toBeRejected()
RxJS observables Subscribe + done, or TestScheduler
setTimeout/setInterval jasmine.clock()
Date.now() jasmine.clock().mockDate()

Pick async/await as your default. Fall back to done when you're working with callbacks or observables that don't convert cleanly to promises. Use jasmine.clock() whenever you have time-dependent logic.


Jasmine async tests verify your code's logic. To verify your application works end-to-end in a real browser — including async flows, loading states, and network calls — HelpMeTest runs automated checks 24/7 without requiring code.

Read more

Start now free