assert.throws()
添加版本:1.0.0.
描述
throws( blockFn, message = "" )
throws( blockFn, expectedMatcher, message = "" )
测试回调函数是否抛出异常,并可以选择比较抛出的错误。
名称 | 描述 |
---|---|
blockFn (函数) |
要执行的函数 |
expectedMatcher |
预期错误匹配器 |
message (字符串) |
断言的简短描述 |
当测试预期在特定情况下抛出异常的代码时,使用 assert.throws()
来捕获错误对象以进行测试和比较。
expectedMatcher
参数可以是
- 一个错误对象。
- 一个错误构造函数,用于使用
errorValue instanceof expectedMatcher
。 - 一个与字符串表示匹配(或部分匹配)的正则表达式。
- 一个回调函数,该函数必须返回
true
才能通过断言检查。
在极少数环境中,例如 Closure Compiler,throws
可能会导致错误。在这种情况下,您可以使用 assert.raises()
。它具有相同的签名和行为,只是名称不同。
变更日志
QUnit 2.12 | 添加了对箭头函数作为 expectedMatcher 回调函数的支持。 |
QUnit 1.9 | assert.raises() 已重命名为 assert.throws() 。assert.raises() 方法仍然作为别名受支持。 |
示例
QUnit.test('throws example', assert => {
// simple check
assert.throws(function () {
throw new Error('boo');
});
// simple check
assert.throws(
function () {
throw new Error('boo');
},
'optional description here'
);
// match pattern on actual error
assert.throws(
function () {
throw new Error('some error');
},
/some error/,
'optional description here'
);
// using a custom error constructor
function CustomError (message) {
this.message = message;
}
CustomError.prototype.toString = function () {
return this.message;
};
// actual error is an instance of the expected constructor
assert.throws(
function () {
throw new CustomError('some error');
},
CustomError
);
// actual error has strictly equal `constructor`, `name` and `message` properties
// of the expected error object
assert.throws(
function () {
throw new CustomError('some error');
},
new CustomError('some error')
);
// custom validation arrow function
assert.throws(
function () {
throw new CustomError('some error');
},
(err) => err.toString() === 'some error'
);
// custom validation function
assert.throws(
function () {
throw new CustomError('some error');
},
function (err) {
return err.toString() === 'some error';
}
);
});