我正在尝试测试某些邮寄代码的失败模式,该模式在最低级别可能会引发错误。测试和抛出的函数之间的所有层都是异步的,并在它们下面的函数上使用await。在最高级别(也在异步函数中,我有一个try catch块。但是,在错误传播到该级别之前,节点抛出未处理的promise异常。
我的测试代码如下所示
beforeEach(function() {
//set default values - tests can change them
this.reasons = '';
this.reschedules = 0;
this.params.cid = 35124;
this.startTest = async () => {
/* this.confirmation is an async function under test,
this.mailer is a mock mailer with an async "send" method
which will throw an error in the correct test */
const doner = this.confirmation(this.mailer);
// ..other actions related to mocking database access made by confirmation
await doner;
return this.mailer.maildata; //provide info on parameters passed to this.mailer
};
});
it('Failure to send is reported', async function() {
this.mailer.sendResolve = false; //tell mock mailer to fail send request
try {
await this.startTest();
expect(true).to.be.false;
} catch(err) {
expect(err).to.be.instanceOf(Error);
}
});
模拟邮件有点像这样
class Mailer {
constructor(user,params){
...
}
...
async send(subject, to, cc, bcc) {
this.maildata.subject = subject;
if (to !== undefined) this.maildata.to = to;
if (cc !== undefined) this.maildata.cc = cc;
if (bcc !== undefined) this.maildata.bcc = bcc;
if (!this.sendResolve) throw new Error('Test Error');
}
...
}
以及测试代码的摘要
module.exports = async function(mailer) {
//get confirm data from database
const cData = await confirm(mailer.params.cid, mailer.db);
if (cData.count > 0) {
// ... format the email message and build it into maildata
await mailer.send(
subject,
emailAddress,
null,
process.env.PAS_MAIL_FROM,
{
pid:cData.pid,
type: 'confirmation',
extra: `Calendar ID ${mailer.params.cid} with procedure ${cData.procedure}`
}
);
debug('message sent, update the database');
await mailer.db.exec(async connection => {
...
});
debug('success');
} else {
debug('invalid calendarid');
throw new Error('Invalid Calendar ID');
}
};
可以看出,从async send
函数返回栈的调用路径try {}catch(){}
都是异步函数。但是,当我运行此测试节点时,会输出未处理的承诺拒绝。
我曾尝试使用Visual Studio代码调试器来完成此步骤,但是我迷上了将异步功能包装成承诺提供者的机制。据我所知,正确处理了一层错误,然后在下一层错误了。
这是否意味着每个异步函数都必须具有try catch块才能捕获并抛出任何错误?我找不到任何说明必须这样做的解释。
要回答您的问题:
这是否意味着每个异步函数都必须具有try catch块才能捕获并抛出任何错误?
错误会await
像您期望的那样通过-ed调用传播:
const assert = require('assert');
const outer = async () => {
await middle();
}
const middle = async () => {
await inner();
}
const inner = async () => {
throw new Error('something bad happened');
}
it('should catch the error', async () => {
let errorMessage;
try {
await outer();
}
catch (err) {
errorMessage = err.message;
}
assert(errorMessage === 'something bad happened'); // Success!
});
...所以,您不需要try / catch
在每个级别都设置障碍。
追踪未处理的Promise
拒绝
await
在您的示例代码中,我看不到链可能在何处断裂,但是为了帮助查找未处理的Promise
拒绝,您可以为unhandledRejection
事件添加一个流程处理程序,并查看日志记录,Promise
以查看拒绝从何处开始并向后追溯从那里调用堆栈:
const assert = require('assert');
const outer = async () => {
await middle();
}
const middle = async () => {
inner(); // <= this will cause an Unhandled Rejection
}
const inner = async () => {
throw new Error('something bad happened');
}
it('should catch the error', async () => {
let errorMessage;
try {
await outer();
}
catch (err) {
errorMessage = err.message;
}
assert(errorMessage === undefined); // Success! (broken await chain)
})
process.on('unhandledRejection', (reason, p) => {
console.log('Unhandled Rejection at:', p);
console.log('reason:', reason);
});
...在这种情况下记录:
Unhandled Rejection at: Promise {
<rejected> Error: something bad happened
at inner (.../code.test.js:12:9)
at inner (.../code.test.js:8:3)
at middle (.../code.test.js:4:9) // <= this is the broken link
at Context.outer (.../code.test.js:18:11)
at callFn (...\node_modules\mocha\lib\runnable.js:387:21)
...
...指向我们的Error
抛出inner
,并通过跟踪环比上涨,我们发现middle
是无效链接。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句