Search code examples
javascriptjasmine-node

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


I have a function that throws an error that I am testing. Here is the function:

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;
    }

When I test this function, I hit the error code and want to validate that an error is being thrown. Here is my test code:

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

But my test fails. Here is my stack trace:

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)

I am using jasmine-expect to test for the error being thrown. What am I doing wrong?


Solution

  • You need to pass a function as parameter to expect in conjunction with toThrow or toThrowError.

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

    or

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