Sinon Stub提供意外的UnhandledPromiseRejectionWarning

时间:2018-05-24 17:13:33

标签: node.js sinon chai chai-as-promised

我有这样的功能:

    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'"));

消除警告的正确方法是什么?奖励:让测试通过。

1 个答案:

答案 0 :(得分:1)

如果未处理拒绝的承诺,即未与Promisecatch(...)链接,则会在最近的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\''
);