Javascript 如何使用Jasmine测试抛出异常对象的函数
使用Jasmine,我想编写一个测试,期望抛出特定类型的异常 我正在使用Crockford推荐的抛出异常的方法 下面的代码可以工作Javascript 如何使用Jasmine测试抛出异常对象的函数,javascript,exception-handling,jasmine,Javascript,Exception Handling,Jasmine,使用Jasmine,我想编写一个测试,期望抛出特定类型的异常 我正在使用Crockford推荐的抛出异常的方法 下面的代码可以工作 describe('toThrow', function() { it('checks that the expected exception was thrown by the actual', function() { var object = { doSomething: function() { thr
describe('toThrow', function() {
it('checks that the expected exception was thrown by the actual', function() {
var object = {
doSomething: function() {
throw {
name: 'invalid',
message: 'Number is invalid'
}
}
};
expect(object.doSomething).toThrow();
});
});
问题是:如何编写此测试,以便它检查抛出的异常名称=='invalid'?可以使用以下方法检查名称和消息:
expect(object.doSomething).toThrow({ name: 'invalid', message: 'Number is invalid' });
可以使用自定义匹配器单独检查名称。改编自内置toThrow:
您只需指定要与之比较的对象:
expect(object.doSomething).toThrow({name: 'invalid', message: 'Number is invalid'});
事实上,我试过了。但是,像这样的测试:expectobject.doSomething.toThrow{name:'a_different_name',message:'Number is invalid';也会过去
expect(object.doSomething).toThrow({name: 'invalid', message: 'Number is invalid'});