我正在使用这段代码:
assert.throws(async () => {
patientSubscriber = await PatientSubscriber.create({
isSubscribed: true,
patient: patient._id,
subscriber: user._id
});
},{
message: /foo/
});
当我运行它时,我得到了这个:
AssertionError [ERR_ASSERTION]: Missing expected exception.
断言 API 是: https://nodejs.org/api/assert.html#assert_assert_throws_fn_error_message
也许我遇到了这个问题? https://github.com/nodejs/node-v0.x-archive/issues/8368
有人知道那个错误是怎么回事吗?
最佳答案
错误意味着没有异常,而这是预期的。 async
函数是 promise 的语法糖。他们从不抛出异常,但可能会返回被拒绝的 promise 。
由于断言应该是同步的,因此不可能以这种方式断言 promise ;整个调用栈应该是基于 promise 的。
正如评论中提到的,assert.rejects
出现在 Node 10 中,导致在断言失败时拒绝 promise 。
如果 promise 由调用者处理(例如在大多数测试框架中),则需要从当前函数返回被拒绝的 promise:
it('...', async () {
await assert.rejects((async () => {})()); // current function returns rejected promise
});
如果断言 promise 未被处理(例如在生产中),它们会导致 UnhandledPromiseRejectionWarning
控制台输出,而不是异常。 unhandledRejection
处理程序可以设置为处理异步错误:
process.on('unhandledRejection', err => {
console.error(err);
process.exit(1);
});
...
assert.rejects((async () => {})());
关于node.js - assert.throws 说 => 缺少预期的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52449922/