'write Jasmine testcase for error cases so that it becomes green

I have a function that returns the largest number of a variant list of parameters, and if there are more than 5 parameters it will throw an error:

if (params.length > 5) {
  throw new Error('Too many arguments');
}

When we write testcase for unit-test in Jasmine, how do we expect the value for the case of such errors (so that the testcase would be successful - green color), because it is not the returned value of the function? Here is my code in testing:

const myLocalVariable1 = require('../src/get-bigest-number');
describe('CommonJS modules', () => {
  it('should import whole module using module.exports = getBiggestNumber;', async () => {
    const result = myLocalVariable1.getBiggestNumber(1, 3, 6, 5, 4, 7);
    expect(result).toBe(new Error('Too many arguments'));
  });
});


Solution 1:[1]

I think it should be like this (Don't assign it to result and then assert result):

expect(myLocalVariable1.getBiggestNumber(1, 3, 6, 5, 4, 7)).toThrow();

You can also do it the stock JavaScript way with try/catch:

it('should import whole module using module.exports = getBiggestNumber;', async () => {
    try {
     const result = myLocalVariable1.getBiggestNumber(1, 3, 6, 5, 4, 7);
    } catch (e) {
     expect(e.message).toBe('Too many arguments');
     // Not sure about the below one but you can try it. We have to use .toEqual and not .toBe since it's a reference type
     expect(e).toEqual(new Error('Too many arguments');
    }
  });

Solution 2:[2]

There is a Jasmine matcher toThrowError that can be used to check that an error is thrown. You can optionally pass a custom error and/or an error message as argument to check that you get the error you expect and not some other error.

In your case, it would be:

expect(() => {
  myLocalVariable1.getBiggestNumber(1, 3, 6, 5, 4, 7);
}).toThrowError('Too many arguments');

Note that you have to place your function call inside another function, otherwise the execution of your function triggers the error and breaks the test.

However, if your function does not take any arguments, you can simply pass the function to the expect:

expect(myFunctionWithNoArgs).toThrowError();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 AliF50
Solution 2