【发布时间】:2014-01-19 19:43:01
【问题描述】:
我正在开发一个大量使用 JavaScript 的应用程序。我需要对这段代码进行单元测试。为了做到这一点,我依靠 Jasmine。
我的一些 JavaScript 代码会抛出 JavaScript Error 对象。这些对象将值分配给 Error 对象的 message 和 name 属性。我为 name 属性分配了一种异常类型。例如,有时名称设置为OutOfRangeException,有时设置为ArgumentException,等等。
如何使用 Jasmine 框架中的toThrowError 函数来测试抛出的错误是否具有特定名称?目前,我的 JavaScript 如下所示:
function getRandomNumber(max) {
if ((!isNaN(parseFloat(max)) && isFinite(max)) === false) {
var error = new Error('You must provide a number');
error.name = 'ArgumentException';
throw error;
}
if ((max === null) || (max < 1) || (max > 100)) {
var error = new Error('The maximum value must be greater than 0 and less than 100.');
error.name = 'ArgumentOutOfRangeException';
throw error;
}
return Math.floor(Math.random() * max) + 1;
}
function ArgumentException(message) {
this.name = 'ArgumentException';
this.message = message || '';
}
ArgumentException.prototype = new Error();
ArgumentException.prototype.constructor = ArgumentException;
如何编写一个检查 ArgumentException 错误或 ArgumentOutOfRangeException 错误的 Jasmine 测试?
谢谢!
【问题讨论】:
-
只是想把这个扔出去:我在使用 jasmine-node npm 包时遇到 toThrowError is not a function failure。原来使用的 Jasmine 版本是 1.3,不支持 toThrowError。使用 toThrow(new Error('the error')) 代替。
标签: unit-testing jasmine