1

我有一些遵循以下结构的 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()
        })
    })
})

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

4

2 回答 2

1

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

于 2018-12-26T15:16:55.650 回答
0

done回调与承诺一起使用是一种反模式。现代测试框架(包括 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({})
        })
    })
})
于 2018-12-26T15:39:26.777 回答