Implementing Asynchronous Tests in Jasmine with Done Callbacks
Jasmine handles asynchronous tests using the 'done' callback in the 'it' block. This prevents tests from completing before async operations resolve, ensuring accurate test results.
15 Mar 2026, 03:35 UTC

Handling Asynchronicity in Jasmine Specifications
The problem often encountered when testing asynchronous code (like API calls or timers) in Jasmine is that tests complete before the asynchronous operation finishes, leading to false failures or misleading successes. The useful takeaway is that Jasmine supports asynchronous testing primarily through the 'done' callback passed into the 'it' block.
Prerequisites for Asynchronous Testing
- A functional Jasmine environment (e.g., configured via Karma or a Node.js runner).
- The code under test must return a Promise or accept a callback for asynchronous operations.
Procedure: Using the 'done' Callback
When defining an asynchronous test, the 'it' block signature must accept a `done` function as an argument. You call `done()` only after the asynchronous operation has fully resolved or rejected.
describe('Async Operation', () => {
it('should complete successfully after a delay', (done) => {
setTimeout(() => {
// Assertion logic here
expect(true).toBe(true);
done(); // Signal completion to Jasmine
}, 100);
});
});
Verification and Checks
To verify this works, run the test suite via your configured runner. A successful run confirms that Jasmine waited for the `done()` call before marking the test as complete.
Concrete Example: Simulated Fetch
If testing a function `fetchData()` that uses a timeout, the test structure would look like this:
it('fetches data correctly', (done) => {
fetchData((data) => {
expect(data).toBeDefined();
done();
});
});
Limitations and Recovery
Limitation: Relying solely on `done()` can lead to 'hanging' tests if `done()` is never called (e.g., due to an unhandled error in the async logic). Recovery: Wrap the asynchronous logic in a `try...catch` block and call `done.fail(error)` within the catch block instead of just `done()`.
Practical Result Check
After running the suite, check the test runner output. A successful asynchronous test will show a single passing test, not an incomplete or timed-out test, confirming the `done()` mechanism functioned correctly.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.