A clean way to test rejected promise

To test the the exception in a rejected promise could be a little bit painful.

And Mocha is Promise-friendly, which means it fails the test if exception is not caught.

So as a result, here is a simple code example to explain how it is being done:

1
2
3
4
5
6
7
8
9
it 'should throw session-expired exception'
new Session().generateId().bindUserFromRedis()
.then ->
null
.catch (ex) ->
ex
.then (ex) ->
expect(ex).to.be.instanceof(ResponseError)
.and.that.have.property('errorName', 'session-expired')

Update: A Chai Plugin can mitigate the pain

1
2
3
4
5
it('should throw session-expired exception', () => {
return expect(new Session().generateId().bindUserFromRedis())
.to.evetually.rejected
.and.that.have.property('errorName', 'session-expired')
})

Update 2: With async, it can be converted into normal test

1
2
3
4
5
it('should throw session-expired exception', () => {
return expect(async () => await new Session().generateId().bindUserFromRedis())
.to.throw
.and.that.have.property('errorName', 'session-expired')
})