node.jsnodeunit

How to assert on error message in nodeunit?


I am trying to write assertions that check error messages in nodeunit. I want the test to fail if the error message doesn't match what I expect. However, it does not seem like the API exists for this. Here is what I am trying to do:

foo.js

function foo() {
  ...
  throw new MyError('Some complex message');
}

foo.test.js

testFoo(test) {
  test.throws(foo, MyError, 'Some complex message');
}

I would like testFoo to fail if the error message is not 'Some complex message', but that's not how it works. It seems like 'Some complex message' is just a message that explains the test failure. It is not involved with the assertion. What is the best way to do this in nodeunit?


Solution

  • The following method of nodeunit API

    throws(block, [error], [message]) - Expects block to throw an error.
    

    can accept a function for the [error] parameter. The function take the actual argument and returns true|false to indicate the success or a failure of the assertion.

    In this way, if you wish to assert that some method throws an Error and that error contains some specific message, you should write a test like this:

      test.throws(foo, function(err) {
        return (err instanceof Error) && /message to validate/.test(err)
      }, 'assertion message');
    

    Example:

    function MyError(msg) {
      this.message = msg;
    }
    MyError.prototype = Error.prototype;
    
    function foo() {
      throw new MyError('message to validate');
    }
    
    exports.testFooOk = function(test) {
      test.throws(foo, function(actual) { 
        return (actual instanceof MyError) && /message to validate/.test(actual) 
      }, 'Assertion message');
      test.done();
    };
    
    exports.testFooFail = function(test) {
      test.throws(foo, function(actual) { 
        return (actual instanceof MyError) && /another message/.test(actual) 
      }, 'Assertion message');
      test.done();
    };
    

    Output:

    āœ” testFooOk
    āœ– testFooFail
    

    Actually any testing framework that implements functions from node.js assert module, support that. For example: node.js assert or Should.js