Node.js assert.throws with async functions(Promises) [英] Node.js assert.throws with async functions (Promises)
问题描述
我想检查是否使用 <$抛出异步函数来自本地断言
模块的c $ c> assert.throws 。
我试过
I want to check if an async function throws using assert.throws
from the native assert
module.
I tried with
const test = async () => await aPromise();
assert.throws(test); // AssertionError: Missing expected exception..
它(obvioulsy?)不起作用,因为函数在Promise解决之前退出。
然而我发现这个问题使用回调获得相同的东西。
It (obvioulsy?) doesn't work because the function exits before the Promise is resolved. Yet I found this question where the same things is attained using callbacks.
有什么建议吗?
(我正在使用Babel转发给Node.js本机生成器)
(I'm transpiling to Node.js native generators using Babel)
推荐答案
由于问题仍然引起关注,我想总结两个最佳解决方案,特别是要强调新的标准方法。
Since the question is still getting attention, I'd like to sum up the two best solutions, especially to highlight the new standard method.
断言库中有一个专用方法, assert.rejects
。
There's a dedicated method in the assert library, assert.rejects
.
来自 vitalets答案的填写:
import assert from 'assert';
async function assertThrowsAsync(fn, regExp) {
let f = () => {};
try {
await fn();
} catch(e) {
f = () => {throw e};
} finally {
assert.throws(f, regExp);
}
}
这篇关于Node.js assert.throws with async functions(Promises)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!