Testing For Exceptions With Jasmine

Marcus T
1 min readDec 2, 2021

When writing unit tests for JavaScript, you may have to cover situations when a function throws an error. With the Jasmine Test Framework, you can accomplish this with awareness of how expecthandles the process flow.

For example, take this function that throws an error if the parameter is not a number or not within a certain range.

const doSomething = num => {
if (!typeof num === 'number') {
throw new TypeError('parameter must be a number');
}
if (num < 0 || n > 100) {
throw new Error('parameter must be in the range [0-100]');
}
...
};

When writing a test for this using Jasmine, you can check if an exception has been thrown with toThrowError.

it('should throw TypeError when parameter is not a number', () => {
expect(doSomething('string')).toThrowError(TypeError);
expect(doSomething(101).toThrowError(Error);
}

However, this does not work. Why? Calling the function doSomething attempts to pass the result into expect. The exception is thrown before expect can actually deal with it. So this test will fail. In order to capture the exception, you must wrap the call in an anonymous function that is invoked by expect.

it('should throw TypeError when parameter is not a number', () => {
const param = 'string';
expect(() => {
doSomething(param);
}).toThrowError(TypeError);
}

Now the error can be captured within the scope of the assertion.

--

--