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

在Mocha/Chai接口测试中,用Promise替代Timeout能否解决超时报错?

用Promise替代done()回调解决Mocha/Chai API测试超时问题

Absolutely! Switching from the done() callback pattern to Promises (or better yet, async/await) is absolutely a better solution for your timeout issues—and it will make your test code cleaner and more maintainable overall.

Your current timeout error Error: timeout of 2000ms exceeded often happens with the done() pattern because:

  • If an error is thrown inside your positiveAssertions or anywhere in the request chain before done() is called, Mocha never gets the signal that the test finished, so it waits until the timeout expires.
  • It’s easy to accidentally forget to call done() in edge cases, leaving Mocha hanging.

Here’s how to refactor your test code to use async/await (a syntactic sugar for Promises that makes asynchronous code read like synchronous code):

describe('Email Tests', function() {
  let messagingApiPath = '/v2/email';
  let testData = require(`../../${testJsonFileName}`);

  // Fixed Chai assertion syntax here (your original == won't trigger a proper assertion failure)
  let positiveAssertions = function(response) {
    console.log('Response : ', response.text);
    expect(response.statusCode).to.equal(200);
    expect(response.status).to.equal(200);
    expect(response.emailReferenceId).to.equal(36);
  };

  describe('POST /v2/email with TO and CC', function() {
    console.log('Test Data File: ' + testJsonFileName);

    describe('with To: CC: Test-Case-1', function() {
      it('response with email id reference expected', async function() {
        // Optional: If your API truly needs more time, increase the timeout here
        this.timeout(5000);

        // Await the request promise instead of using .end(done)
        const response = await request
          .post(messagingApiPath)
          .send(input);
        
        // Run your assertions after the response is received
        positiveAssertions(response);
      });
    });

    // Repeat this pattern for your other test cases
  });
});

Why this is better than done():

  • No more hanging tests: Mocha automatically waits for the Promise returned by the async function to resolve or reject. If an error is thrown (like an assertion failure), Mocha catches it immediately instead of waiting for a timeout.
  • Cleaner code: async/await eliminates callback nesting and makes the flow of your test easy to follow.
  • Better error handling: Any error in the request or assertion pipeline will be properly propagated to Mocha, so you’ll get clear error messages instead of a generic timeout.
  • Flexibility: If you do need longer timeouts for slow API endpoints, you can still set this.timeout() in individual test cases or describe blocks.

One quick note about your original code: expect(response.emailReferenceId == 36); isn’t using Chai’s assertion syntax correctly. This line just evaluates a boolean but doesn’t tell Chai to check it—so if emailReferenceId isn’t 36, your test won’t fail! Fixed that in the refactored code with .to.equal(36).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:40:27