Using toThrowError in Jasmine

末鹿安然 提交于 2019-12-02 20:48:27

Checking exception for a function with parameter is not supported in jasmine. But you can use below workaround to overcome this limitation and test your functions.

describe('toThrowError test case', function() {

    it('test getRandomNumber function for undefined', function() {
        expect(function() {
            getRandomNumber(undefined);
        }).toThrowError("You must provide a number");
    });

    it('test getRandomNumber function for 0', function() {
        expect(function() {
            getRandomNumber(0);
        }).toThrowError("The maximum value must be greater than 0 and less than 100.");
    });

});

toThrowError matcher takes 1 or 2 parameters

  • 1 Parameter - Either exception message or exception type
  • 2 Parameters - Exception type and Exception message

Example to check based on exception type:

function getRandomNumber(max) {
    throw new SyntaxError();
}

describe('toThrowError test case', function() {
    it('test getRandomNumber function for undefined', function() {
        expect(function() {
            getRandomNumber(undefined);
        }).toThrowError(SyntaxError);
    });
});

Refer link for different types of exceptions.

Custom Error Message

Below mentioned snippet gives a sample for using the custom error messages.

function getRandomNumber(max) {
    throw new ArgumentException();
}

function ArgumentException(message) {
  this.name = 'ArgumentException';
  this.message = message || '';
}

ArgumentException.prototype = new Error();
ArgumentException.prototype.constructor = ArgumentException;

describe('toThrowError test case', function() {
    it('test getRandomNumber function for undefined', function() {
        expect(function() {
            getRandomNumber(undefined);
        }).toThrowError(ArgumentException);
    });
});

If would like to pass your test as soon as your method throws an Error. Then you could use try-catch block and when you reach the catch block, you expect your test to be passed.

function ErrorFunction(args:any[]) {
    throw new Error('An error message');
}

describe('Testing a function that throws an error',()=>{
    it('should throw an Error',()=>{
        try { 
        ErrorFunction(args) 
        } catch (e) {
        expect(true).toBeTruthy();
        }
    })
})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!