【问题标题】:UnhandledPromiseRejectionWarning on test failureUnhandledPromiseRejectionWarning 测试失败
【发布时间】:2018-12-26 15:08:37
【问题描述】:

我有一些 mocha/chai/chai-http 测试遵循以下结构,但是每当一个测试失败时,我都会得到一个 UnhandledPromiseRejectionWarning,我似乎无法弄清楚它的来源。

UnhandledPromiseRejectionWarning:未处理的承诺拒绝。这 错误源于在异步函数内部抛出 没有 catch 块,或拒绝未处理的承诺 使用 .catch()。

describe('indexData', () =>{
    it('Should return status code 200 and body on valid request', done => {
        chai.request(app).get('/api/feed/indexData')
            .query({
            topN: 30,
            count: _.random(1, 3),
            frequency: 'day'
        })
            .set('Authorization', token).then(response => {
            // purposefully changed this to 300 so the test fails
            expect(response.statusCode).to.equal(300)
            expect(response.body).to.not.eql({})
            done()
        })
    })
})

我尝试在.then() 之后添加.catch(err => Promise.reject(err),但它也不起作用。我可以在这里做什么?

【问题讨论】:

    标签: node.js mocha.js chai chai-http


    【解决方案1】:

    我通过添加.catch(err => done(err)) 解决了这个问题

    【讨论】:

      【解决方案2】:

      done 回调与 Promise 一起使用是一种反模式。现代测试框架(包括 Mocha)支持 Promise。应该从测试中返回一个承诺:

      it('Should return status code 200 and body on valid request', () => {
            return chai.request(app).get('/api/feed/indexData')
              .query({
                topN: 30,
                count: _.random(1, 3),
                frequency: 'day'
              })
              .set('Authorization', token).then(response => {
                // purposefully changed this to 300 so the test fails
                expect(response.statusCode).to.equal(300)
                expect(response.body).to.not.eql({})
              })
          })
      })
      

      【讨论】:

      • 啊好吧我不知道。如果我想使用 done 而不是 promises 呢?
      • 但是你已经有了一个可以使用的承诺,这就是为什么它是反模式的。如果没有承诺,done 可能是合适的。
      • 知道了。谢谢。
      猜你喜欢
      • 2019-04-28
      • 2018-06-14
      • 2020-04-21
      • 1970-01-01
      • 2013-10-23
      • 2011-02-16
      • 2021-07-03
      • 2017-04-02
      相关资源
      最近更新 更多