我有一个函数会抛出我正在测试的错误。这是函数:
parse: function(input) {
var results = {};
var that = this;
input.forEach(function(dependency) {
var split = dependency.split(": ");
var lib = split[0];
var depen = split[1];
if(depen === undefined) {
throw new Error('Invalid input. Requires a space after each colon.')
}
results[lib] = depen;
});
return results;
}
当我测试这个函数时,我遇到了错误代码并想验证是否抛出了错误。这是我的测试代码:
var invalidInput = ['Service1: ', 'Service2:stuff']
expect(manager.parse(invalidInput)).toThrowError();
但是我的测试失败了。这是我的堆栈跟踪:
Failures:
1) dependency.js input should require a space after each colon as specified by requirements
Message:
Error: Invalid input. Requires a space after each colon.
Stacktrace:
Error: Invalid input. Requires a space after each colon.
at /Users/name/Development/sight/dependency.js:49:11
at Array.forEach (native)
at Object.module.exports.parse (/Users/name/Development/sight/dependency.js:44:9)
at null.<anonymous> (/Users/name/Development/sight/spec/dependency.spec.js:34:12)
我正在使用 jasmine-expect
来测试抛出的错误。我做错了什么?
最佳答案
您需要将函数作为参数传递给 expect
以及 toThrow
或 toThrowError
。
var invalidInput = ['Service1: ', 'Service2:stuff']
expect(function () { manager.parse(invalidInput); }).toThrow();
或
var invalidInput = ['Service1: ', 'Service2:stuff']
expect(function () { manager.parse(invalidInput); }).toThrowError(Error);
关于javascript - 为什么 jasmine-expect 不验证是否抛出了错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29541046/