I am trying to perform Chai testing on several functions and have hit a roadblock of sorts. The particular function I am calling should throw an exception under certain conditions. I set breakpoints and could see where it threw the exception but it never propagates out to the expect function. I keep getting this error:
AssertionError: expected [Function] to throw 'InvalidInviteException: This is not a valid invite.'
Expected :"InvalidInviteException: This is not a valid invite."
Actual :[undefined]
export const createInviteDomainOwner = () => {
const inviteDomainOwner = async ({
emailAddress,
firstName,
lastName,
domainId
}) => {
try {
throw new InvalidInviteException('This is not a valid invite.');
} catch (e) {
throw e;
}
}
return {
inviteDomainOwner
}
}
it('invite domain owner', async function() {
const {inviteDomainOwner} = createInviteDomainOwner();
await expect(() => inviteDomainOwner({
emailAddress: 'abc123abc@test.com',
firstName: 'John',
lastName: 'Doe',
domainId: '1111-1111-1111-1111'
}).to.throw(new InvalidInviteException('This is not a valid invite.'));
});
How should I organize my try/catch exception handling for this to work as expected?
@jonrsharpe's suggestion is correct, chai-as-promised will do this. I give you a fully working example.
Chai as Promised extends Chai with a fluent language for asserting facts about promises.
import chai, { expect } from 'chai';
import chaiAsPromised from 'chai-as-promised';
chai.use(chaiAsPromised);
class InvalidInviteException extends Error {}
export const createInviteDomainOwner = () => {
const inviteDomainOwner = async ({ emailAddress, firstName, lastName, domainId }) => {
try {
throw new InvalidInviteException('This is not a valid invite.');
} catch (e) {
throw e;
}
};
return {
inviteDomainOwner,
};
};
it('invite domain owner', async function () {
const { inviteDomainOwner } = createInviteDomainOwner();
await expect(
inviteDomainOwner({
emailAddress: 'abc123abc@test.com',
firstName: 'John',
lastName: 'Doe',
domainId: '1111-1111-1111-1111',
}),
).to.eventually.rejectedWith(InvalidInviteException, 'This is not a valid invite.');
});
"chai": "^4.2.0",
"chai-as-promised": "^7.1.1",