Reputation: 1241
I wrote a function that takes some arguments and inside the function it uses a class that has a function from a 3rd party library that returns a promise and I return this result of the promise in my own function. like :
return client.track(data) // client.track is from a 3rd party lib that should return a promise
Now I want to test the return of the promise in my mocha + chai testing file. I import this function with the inputs and I should get the result. something like:
const result = await myfunc(x,y) // Should return the result of a promise
now I want to test if the promise was actually resolved or rejected in mocha + chai, like using
chai.expect(...)
How can I do this?
Upvotes: 0
Views: 1706
Reputation: 36
Maybe you need a specific assertion inside the catch section, something like:
chai.expect(e).to.be.an.instanceOf(Error);
chai.expect(e.message).to.be.not.null;
The expect method comes from the chai library which usually partners with mocha.
Upvotes: 0
Reputation: 837
Here's what I am using with mocha
to test rejected promises. It is ugly and verbose, but avoids adding more test dependencies, and avoids false positives.
describe('when an awaited promise is rejected', () => {
it('should raise an error', async () => {
try {
await someAsyncFunctionThatWillReject()
assert(false) // will fail the test if no error
} catch(e) {
assert(true) // passes only if there was an error
}
})
})
The final assert(true)
does not really affect test results, but it makes the test more readable.
Upvotes: 0
Reputation: 31909
This works, but requires a little bit of boilerplate.
await expect(await myPromise.then(() => true)).to.be.true
Upvotes: 0
Reputation: 374
Take a look at the npm package chai-as-promised
(https://www.npmjs.com/package/chai-as-promised). It's an extension to the chai library which offers support for promises.
You can set it up in the following way
const chai = require("chai")
const chaiAsPromised = require("chai-as-promised")
chai.use(chaiAsPromised)
chai.should()
promiseFunction(args).should.be.rejectedWith(SomeError)
promiseFunction().should.eventually.be.a('array')
Take a look at the documentation to get a better idea of the power of this plugin :)
Upvotes: 2