我有这样的功能:
static async performDatabaseConnectivityHealthCheck(logger) {
let con;
let ret;
try {
con = mysql.createConnection({
host: config.db.host,
user: config.db.user,
password: config.db.password,
database: config.db.db,
});
const { retData } = await sqlFileReader.read('./src/database/sql/healthcheck.sql', [config.db.db], con, logger);
// Do something with retData.....
}
catch (error) {
logger.error(error.message);
throw error;
}
finally {
if (con) {
con.end();
}
}
return ret;
}
这样的测试:
it('throws a \'Database Healthcheck Error\' error when the Database Healthcheck gives the wrong data', async () => {
//Some irrelevant details here including providing rars for rars.logger in the following...
sandbox.stub(sqlFileReader, 'read').returns(Promise.reject(new Error("ER_PROCACCESS_DENIED_ERROR: execute command denied to user 'dchambers'@'%' for routine 'uk_txtloan.connection_ids'")));
expect(async () => {
await RiskAffordabilityReportService.performDatabaseConnectivityHealthCheck(rars.logger);
}).to.throw('ER_PROCACCESS_DENIED_ERROR: execute command denied to user \'dchambers\'@\'%\' for routine \'uk_txtloan.connection_ids\'');
});
我有两个问题。首先,sandbox.stub
行给出了以下警告,我很困惑,因为我要求承诺被拒绝!
UnhandledPromiseRejectionWarning: Error: ER_PROCACCESS_DENIED_ERROR: execute command denied to user 'dchambers'@'%' for routine 'uk_txtloan.connection_ids'
其次,测试没有通过:
AssertionError: expected [Function] to throw an error
。
我主要想知道这个警告。我尝试了以下语法,它们也给出了同样的错误:
sandbox.stub(sqlFileReader, 'read').throws(new Error("ER_PROCACCESS_DENIED_ERROR: execute command denied to user 'dchambers'@'%' for routine 'uk_txtloan.connection_ids'"));
sandbox.stub(sqlFileReader, 'read').resolves(Promise.reject(new Error("ER_PROCACCESS_DENIED_ERROR: execute command denied to user 'dchambers'@'%' for routine 'uk_txtloan.connection_ids'")));
sandbox.stub(sqlFileReader, 'read').rejects(new Error("ER_PROCACCESS_DENIED_ERROR: execute command denied to user 'dchambers'@'%' for routine 'uk_txtloan.connection_ids'"));
消除警告的正确方法是什么?奖励:让测试通过。
答案 0 :(得分:1)
如果未处理拒绝的承诺,即未与Promise
或catch(...)
链接,则会在最近的then(..., ...)
实施中抛出未处理的承诺拒绝错误。
Chai to.throw
断言包含try..catch
的函数,但async
函数不会抛出任何错误。 async
函数是返回promise的函数的语法糖。 async
函数中未捕获的错误导致返回被拒绝的承诺。相反,应该用chai-as-promise断言断言:
expect(RiskAffordabilityReportService.performDatabaseConnectivityHealthCheck(rars.logger))
.to.be.rejectedWith(
Error,
'ER_PROCACCESS_DENIED_ERROR: execute command denied to user \'dchambers\'@\'%\' for routine \'uk_txtloan.connection_ids\''
);