【问题标题】:Mocha is throwing Promise rejection error in Test expect error condition. How to fix this?Mocha 在测试预期错误条件下抛出 Promise 拒绝错误。如何解决这个问题?
【发布时间】:2020-03-12 08:27:12
【问题描述】:

我正在使用 Mocha 和 Chai 进行单元测试。我的测试用例如下所示。

describe('1. Users APIs', () => {
    it('1.1 Get Users', (done) => {
        controller.getCaseDetails(req, res, () => { }).then(data => {
            except(data).to.be.have.property(statusCode, 400);
            done();
        });
    });
});

如果测试用例失败,那么我将遇到错误。

  1) 1. Users APIs.
       1.1 Get Users:
     Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (/home/techjini/Techjini/node-projects/CollectionsApp-NodeJS/src/cases/test/getCases.test.js)
      at listOnTimeout (internal/timers.js:549:17)
      at processTimers (internal/timers.js:492:7)

为了解决这个问题,我将 .catch 添加到然后阻塞和 done() 内捕获。然后测试成功了。如何解决这个问题。

根据我的回溯,我知道如果我添加了 catch 块,则会处理错误,但如果我没记错的话,mocha 不会出现任何断言错误。

我想打印正确的错误消息以防except 失败。

我们将不胜感激任何形式的帮助。

【问题讨论】:

    标签: node.js mocha.js chai


    【解决方案1】:

    您需要为异步请求设置超时,如下所示:

    describe('Live Agent', function () {
        //set timeout for this test suit
        this.timeout(25000);
        describe('createRequest', function () {
            it(" Live agent request is created", function (done) {
                supertestAgent
                    .post(apiPath + "/createRequest")
                    .send({
                        "dialogId": "5e427fc25c790ffa5c727a",
                        "platform": "fb",
                        "endUser": { id: "fsfg" }
                    })
                    .end(function (err, result) {
                        expect(err).equals(null);
                        expect(result.status).equals(201)
                        done();
                    });
            })
        });
    

    在上面的代码示例中,超时设置为顶部容器,因此下面的所有测试用例都将继承超时。

    this.timeout(25000)
    

    Moacha 直接打印断言错误,因此我们无法访问它。因此,您需要在防止expect 失败的同时添加更多测试用例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-10
      • 2018-01-27
      • 2015-12-10
      • 1970-01-01
      • 2012-01-22
      • 2021-09-14
      • 2021-07-25
      • 2015-12-30
      相关资源
      最近更新 更多