I have this exported function:
module.exports.doThing = async (input) => {
if(input === '') { throw('no input present') }
// other stuff
return input
}
and a test file for it, in which I'm trying to test that an error is thrown when input is invalid. This is what I've tried:
const testService = require('../services/testService.js')
const chai = require('chai')
const expect = chai.expect
const sinon = require('sinon')
chai.use(require('sinon-chai'))
describe('doThing', () => {
it('throws an exception if input is not present', async () => {
expect(testService.doThing('')).to.be.rejected
})
})
I'm getting the error Error: Invalid Chai property: rejected
and also UnhandledPromiseRejectionWarning
How can I fix this test?
You can to install the plugin chai-as-promised
. This allows you to do the following:
const testService = require('../services/testService.js')
const chai = require('chai')
.use(require('chai-as-promised'))
const expect = chai.expect;
describe('doThing', () => {
it('throws an exception if input is not present', async () => {
await expect(testService.doThing('')).to.be.rejectedWith('no input present');
});
it('should not throw ...', async () => {
await expect(testService.doThing('some input')).to.be.fulfilled;
});
})