如何断言nodeunit中的错误消息?

我试图编写断言,检查nodeunit中的错误消息。 如果错误信息与我期望的不符,我想testing失败。 但是,它似乎不存在这样的API。 这是我正在做的事情:

foo.js

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

foo.test.js

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

如果错误消息不是 “一些复杂的消息”,我想要testFoo失败,但这不是它的工作原理。 看起来像“一些复杂的信息”只是一个解释testing失败的信息。 它不涉及这个断言。 什么是最好的方式来做到这一点在nodeunit?

下面的nodeunit API的方法

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

可以接受[error]参数的function。 该函数采用actual参数并返回true|false来表示断言的成功或失败。

这样,如果你想断言某些方法抛出一个Error并且该错误包含一些特定的消息,你应该写一个像这样的testing:

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

例:

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

输出:

 ✔ testFooOk ✖ testFooFail 

实际上任何从node.js实现函数的testing框架都声明模块,支持这个。 例如: node.js断言或Should.js