You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

mysql2升级后健康检查代码修改引发Sinon测试报错及Promise警告问题

MySQL2升级后健康检查代码及测试问题

我正在将部分MySQL数据库迁移至更高主版本,同时有多个Node.js项目依赖这些数据库。为适配新版本MySQL,我升级了mysql2依赖包及Node.js版本,但原有MySQL健康检查代码在新版mysql2下无法运行:

const check = {
  mysql: client =>
    cb => client.query('SELECT 1+1 AS result', error => cb(null, {
      success: !error,
      details: { error },
    }))
}

报错信息:Callback function is not available with promise clients.

于是我将代码修改为:

const check = {
  mysql: client =>
    cb => client.query('SELECT 1+1 AS result')
      .then(_ => {
        cb(null, {
          success: true,
        });
      })
      .catch(err => {
        cb(null, {
          success: !err,
          details: { err },
        })})
}

不确定该修改是否能修复健康检查,但它导致测试代码报错。测试代码如下:

it('should return when client does not returns an err', (done) => {
      const fakeClient = { query: sinon.stub().yieldsAsync(null) };

      const mysqlCheck = check.mysql(fakeClient);

      mysqlCheck((err, report) => {
        expect(fakeClient.query).calledWith('SELECT 1+1 AS result');

        expect(err).not.to.exist;
        expect(report.success).to.be.true;
        expect(report.details.error).to.not.exist;
        done();
      });
    });

报错信息:TypeError: stub expected to yield, but no callback was passed. Received [SELECT 1+1 AS result]

我尝试调整测试代码但效果不佳,不清楚问题所在,希望得到指引。


更新

感谢@Bergi的建议,我将stub修改为:

const fakeClient = { query: () => Promise.resolve() };
sinon.stub(fakeClient, 'query').resolves().callsFake(() => {
  return Promise.resolve({
    success: true
  });
});

测试已通过,但出现警告:UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): AssertionError: expected false to be true

请问该警告是否可以忽略,还是需要处理?


内容的提问来源于stack exchange,提问作者Gael

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 07:32:46