Sinon Stub 给出了意想不到的 UnhandledPromiseRejectionWarning

Sinon Stub gives unexpected UnhandledPromiseRejectionWarning

我有这样的功能:

    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 行给出了以下警告,我对此感到困惑,因为我要求 Promise 被拒绝!

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

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

如果未处理被拒绝的承诺,即未与 catch(...)then(..., ...) 链接,则在最近的 Promise 实施中会抛出未处理的承诺拒绝错误。

Chai to.throw 断言用 try..catch 包装了一个函数,但在 async 函数中没有抛出错误。 async 函数是 returns 承诺的函数的语法糖。 async 函数内未捕获的错误导致返回被拒绝的承诺。相反,它应该使用 chai-as-promised 断言来断言:

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