为什么jasmine期望不验证错误被抛出?

时间:2015-04-09 14:16:11

标签: javascript jasmine-node

我有一个函数会抛出我正在测试的错误。这是功能:

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来测试引发的错误。我做错了什么?

2 个答案:

答案 0 :(得分:7)

您需要将作为参数的函数与expecttoThrow一起传递给toThrowError

var invalidInput = ['Service1: ', 'Service2:stuff'] 
expect(function () { manager.parse(invalidInput); }).toThrow();

var invalidInput = ['Service1: ', 'Service2:stuff'] 
expect(function () { manager.parse(invalidInput); }).toThrowError(Error);

答案 1 :(得分:0)

Seens toThrowError要求参数。尝试设置参数:它可以是预期的错误消息或类型,或两者兼而有之。

expect(manager.parse(invalidInput)).toThrowError('Invalid input. Requires a space after each colon.');

要忽略错误消息,您可以使用toThrow。来自documentation

it("The 'toThrow' matcher is for testing if a function throws an exception", function() {
    var foo = function() {
      return 1 + 2;
    };
    var bar = function() {
      return a + 1;
    };

    expect(foo).not.toThrow();
    expect(bar).toThrow();
  });

  it("The 'toThrowError' matcher is for testing a specific thrown exception", function() {
    var foo = function() {
      throw new TypeError("foo bar baz");
    };

    expect(foo).toThrowError("foo bar baz");
    expect(foo).toThrowError(/bar/);
    expect(foo).toThrowError(TypeError);
    expect(foo).toThrowError(TypeError, "foo bar baz");
  });
});