UnhandledPromiseRejectionWarning 测试失败

UnhandledPromiseRejectionWarning on test failure

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

UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .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),但它也没有用。我可以在这里做什么?

我通过添加 .catch(err => done(err))

解决了这个问题

done 回调与 promises 一起使用是一种反模式。 Promises 得到现代测试框架的支持,包括 Mocha。应从测试中返回承诺:

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({})
        })
    })
})