Skip to content

Instantly share code, notes, and snippets.

@mfdj
Created July 19, 2021 22:21
Show Gist options
  • Save mfdj/e9aff374d040531a0e34860f4b099888 to your computer and use it in GitHub Desktop.
Save mfdj/e9aff374d040531a0e34860f4b099888 to your computer and use it in GitHub Desktop.
jest await expect(testSubject()).rejects.toThrow expects the rejected value to be an Error object otherwise just use `rejects.toMatch`
// test subjects
const rejectsStringValue = () => Promise.reject('I rejected');
const rejectsErrorValue = () => Promise.reject(new Error('I rejected'));
// tests
describe('rejectsStringValue', () => {
it('will throw in try/catch', async () => {
expect.assertions(1);
try {
await rejectsStringValue();
} catch (e) {
expect(e).toBe('I rejected');
}
});
it('when passing the test-subject as reference', async () => {
await expect(rejectsStringValue).rejects.not.toThrow();
await expect(rejectsStringValue).rejects.toMatch('I rejected');
});
it('when executing the test-subject in the expect', async () => {
await expect(rejectsStringValue()).rejects.not.toThrow();
await expect(rejectsStringValue()).rejects.toMatch('I rejected');
});
});
describe('rejectsErrorValue', () => {
it('will throw in try/catch', async () => {
expect.assertions(1);
try {
await rejectsErrorValue();
} catch (e) {
expect(e).toEqual(new Error('I rejected'));
}
});
it('when passing the test-subject as reference', async () => {
await expect(rejectsErrorValue).rejects.toThrow('I rejected');
});
it('when executing the test-subject in the expect', async () => {
await expect(rejectsErrorValue()).rejects.toThrow('I rejected');
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment