Last active
October 1, 2022 22:12
-
-
Save joeskeen/d9c053b947e5e7462e8d978286311e83 to your computer and use it in GitHub Desktop.
Different ways of handling/expecting errors when testing using Jest (both synchronous and asynchronous)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
describe("testing error cases in Jest", () => { | |
describe("errors (vanilla Jest)", () => { | |
describe("when thrown synchronously", () => { | |
function synchronousError() { | |
throw new Error(""); | |
} | |
it("should require expect(action).toThrow()", () => { | |
const action = () => synchronousError(); | |
expect(action).toThrow(); | |
}); | |
it("can use try/catch", () => { | |
try { | |
synchronousError(); | |
// note: requires the "jest-jasmine2" test runner: | |
fail("it should have thrown an error..."); | |
} catch (err) { | |
expect(err).toBeDefined(); | |
} | |
}); | |
}); | |
describe("when thrown asynchronously", () => { | |
async function asynchronousError() { | |
await new Promise((resolve) => setTimeout(resolve)); | |
throw new Error(""); | |
} | |
it("should require expect(action).rejects.toThrow() (no await)", () => { | |
const action = () => asynchronousError(); | |
expect(action).rejects.toThrowError(""); | |
}); | |
}); | |
describe("when throw happens before await in async function", () => { | |
async function asynchronousErrorBeforeAwait( | |
shouldThrow = true, | |
result: string = undefined | |
) { | |
if (shouldThrow) throw new Error(""); | |
await new Promise((resolve) => setTimeout(resolve)); | |
return result; | |
} | |
describe("when thrown synchronously in an async function", () => { | |
it("should require expect(action).rejects.toThrow()", () => { | |
const action = () => asynchronousErrorBeforeAwait(); | |
expect(action).rejects.toThrow(); | |
}); | |
}); | |
describe("when not thrown", () => { | |
it("should be awaited", async () => { | |
const result = await asynchronousErrorBeforeAwait(false, "YAY"); | |
expect(result).toBe("YAY"); | |
}); | |
}); | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment