Home > OS >  write Jasmine testcase for error cases so that it becomes green
write Jasmine testcase for error cases so that it becomes green

Time:04-22

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'));
  });
});

CodePudding user response:

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');
    }
  });

CodePudding user response:

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

  • Related