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

使用Mocha、Chai和Sinon时遇到未处理的Promise拒绝警告

Fixing Unhandled Promise Rejection Warnings in Mocha/Chai/Sinon Tests for Your Node.js ES6 Class

Let's break down why you're seeing that unhandled Promise rejection warning and how to fix it step by step.

First, Understand the Root Cause

Your prepareInputParameters method is marked async, which means it always returns a Promise. If any error occurs inside it (or if you forget to handle async operations properly), that Promise will reject. If your test doesn't explicitly handle that rejection, Mocha will throw the warning you're seeing.

Let's cover the most common fixes:

1. Fix Your Test to Handle Async Properly

Mocha needs to know when your async test is complete, and it needs to catch any rejected Promises. Here are the right ways to write your test:

Option A: Use async/await with try/catch

const { expect } = require('chai');
const ParameterParser = require('../path/to/your/class');
const Lnfe = require('../errors/LoanNotFoundError');

describe('ParameterParser', () => {
  describe('#prepareInputParameters', () => {
    it('should return correct clientId and dateString', async () => {
      // Mock your con and req objects first (use Sinon if needed)
      const mockCon = {};
      const mockReq = { query: { client_id: '123' } };

      try {
        const result = await ParameterParser.prepareInputParameters(mockCon, mockReq);
        // Add your assertions here
        expect(result.clientId).to.equal('123');
        expect(result.dateString).to.be.a('string');
      } catch (err) {
        // If you expect an error, assert it here
        expect(err).to.be.an.instanceOf(Lnfe);
      }
    });
  });
});

Option B: Return the Promise and Use Chai-as-Promised (if you have it installed)

If you use chai-as-promised, you can make your tests cleaner:

it('should resolve with valid parameters', () => {
  const mockCon = {};
  const mockReq = { query: { client_id: '123' } };
  
  return expect(ParameterParser.prepareInputParameters(mockCon, mockReq))
    .to.eventually.have.property('clientId', '123');
});

it('should reject with LoanNotFoundError when loan is missing', () => {
  const mockCon = {};
  const badReq = { query: {} }; // No client_id or invalid loanId
  
  return expect(ParameterParser.prepareInputParameters(mockCon, badReq))
    .to.be.rejectedWith(Lnfe);
});

2. Ensure Your Async Method Handles Internal Async Operations Correctly

Looking at your code snippet, if you add async logic (like database calls with con or sqlFileReader), you must await those operations. Forgetting to do this will leave unhandled Promises floating around:

static async prepareInputParameters(con, req) {
  let clientId = req.query.client_id;
  
  // Example: If you need to fetch clientId from loanId via DB
  if (!clientId && req.query.loan_id) {
    // Await the async DB call so any rejection is propagated
    const loan = await con.query('SELECT client_id FROM loans WHERE id = ?', [req.query.loan_id]);
    if (!loan) {
      throw new Lnfe('Loan not found'); // This becomes a rejected Promise
    }
    clientId = loan.client_id;
  }
  
  const dateString = moment().format('YYYY-MM-DD');
  return { clientId, dateString }; // Return the expected values
}

3. Fix Sinon Stubs for Async Dependencies

If you're stubbing async functions (like sqlFileReader or database calls), make sure your stubs return Promises:

const sinon = require('sinon');
const sqlFileReader = require('../database/SqlFileReader');

// Stub a successful async call
sinon.stub(sqlFileReader, 'readSomeFile').resolves({ clientId: '456' });

// Stub a failed async call (to test error handling)
sinon.stub(sqlFileReader, 'readSomeFile').rejects(new Lnfe('Loan not found'));

Key Takeaways

  • Always await async operations inside your async method to propagate rejections properly.
  • Never leave an async function call hanging in your test—either await it, return it, or use Chai-as-Promised to handle the Promise.
  • Make sure your method returns the expected value (per your JSDoc comment) so the Promise resolves with meaningful data.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:54:05