为什么 jasmine-expect 不验证是否抛出了错误?

Why is jasmine-expect not validating that an error was thrown?

我有一个函数在测试时会抛出一个错误。这是函数:

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

看到 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");
  });
});

您需要将函数作为参数传递给 expect 以及 toThrowtoThrowError

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

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