【问题标题】:Getting error " Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called;"出现错误“错误:超过 2000 毫秒的超时。对于异步测试和挂钩,请确保调用了“done()”;”
【发布时间】:2026-01-31 01:45:01
【问题描述】:

我看到以下使用 mochachai 库的测试用例。 Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

这里是 code 用于测试亚马逊 lambda 函数的处理程序。(目前,我没有使用 super-test npm 模块)

const expect = require('chai').expect;
const mongoose = require('mongoose');
const CONFIG_DEV_MONGODB = require('../../config/config.dev').DB_CONNECTION_URL;


describe('get the foo', () => {

    let handler;
    before(() => {

        process.env.DEPLOYMENT_STAGE = 'test';
        process.env.DB_CONNECTION_URL = CONFIG_DEV_MONGODB;
        handler = require('./get');
    });

    after(() => {

        if (mongoose.connection) {
            mongoose.connection.close();
        }
    });

    it('validate getFeaturedProducts get request with storeid',function(done){
        //request has the sample data for event
        let request = require('../../test/fixtures/featureProductJSON');
        handler.getFeaturedProducts(request, {} , (error, result) => {

             expect(error).to.be.null;
             expect(result).to.be.not.null;
             done()
         })

    })
});

这里是处理程序

module.exports.getFeaturedProducts = function (event, context, callback) {
    ..............
    .......
    mongoConnection.then( function() {
         return callback(null, 'test');
     }, function (error) {

        return return callback(true, null);;
    })
 }

谁能解释一下发生了什么

【问题讨论】:

    标签: node.js mocha.js chai


    【解决方案1】:

    您的测试花费的时间比 Mocha 预期的要长并且超时。默认情况下,所有回调函数在 2000 毫秒后超时。您需要使用this.timeout() 调整测试套件的超时时间。

    您可以在 describe() 中的套件级别指定此内容:

    describe('get the foo', function () {
      this.timeout(10000) // all tests in this suite get 10 seconds before timeout
    
      // hooks & tests
    })
    

    你可以在像before()这样的钩子中指定这个:

    describe('get the foo', function() {
        before(function() {
          this.timeout(10000) // 10 second timeout for setup
        })
    
        // tests
    })
    

    您也可以在 it() 中的测试级别执行此操作

    describe('get the foo', function () {
      it('validate getFeaturedProducts get request with storeid', function (done) {
        this.timeout(10000) // 10 second timeout only for this test
    
        // assertions
      })
    })
    

    【讨论】:

    • TypeError: this.timeout is not a function 给出以下错误。
    • 在 Mocha 中根本不能使用箭头函数。您需要使用普通的旧 function() {} 语法。使用 Mocha 时,箭头函数会破坏 this 绑定。你可以阅读更多关于它的信息here。请注意我的所有示例都使用function() {} 而不是() => {}。如果您查看链接中的示例,您会看到他们给出的确切示例是破坏 this.timeout() 的箭头函数。
    • @made_in_india 在整个帖子中,甚至在最后的评论中,都建议不要使用箭头函数。但是,根据该问题线程中的评论,您似乎可以将timeout() 链接到it() 但是,只有it() 通过it().timeout()
    【解决方案2】:

    帮助将.timeout(10000)添加到函数it()的末尾

    describe('Reverse String Test', () => {
    
     it('Compare first data',  async function () {
         try {
            await sql.connect(config);
    
            let request = await new sql.Request()
             .query('SELECT count(*) FROM dbo.valJob');
                 console.log(request);
            await sql.close();
    
        } catch (err) {
            console.log(err)
        }
    
     }).timeout(10000);
    });
    

    【讨论】:

      【解决方案3】:

      防止这种情况的另一种方法。您只需将Mocha 默认超时2000ms 修改为10000ms。 要在您的 package.json 上添加 --timeout 标志,例如:

      "scripts": {
         // rest of your scripts
         "test": "mocha server/**/*.test.js --timeout 10000"
      },
      

      【讨论】:

        最近更新 更多