Search code examples
node.jsmocha.jschaichai-http

UnhandledPromiseRejectionWarning on test failure


I have some mocha/chai/chai-http tests that follow the below structure however whenever one test fails I get an UnhandledPromiseRejectionWarning which I can't seem to figure out it's source.

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

I tried adding a .catch(err => Promise.reject(err) after the .then() but it didn't work either. What can I do here?


Solution

  • The use of done callback together with promises is an antipattern. Promises are supported by modern testing frameworks, including Mocha. A promise should be returned from a test:

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