Skip to content

Instantly share code, notes, and snippets.

@nazmulidris
Last active February 10, 2022 00:57
Show Gist options
  • Save nazmulidris/cbcc3dcd1b968eef6e370d8f5f642b67 to your computer and use it in GitHub Desktop.
Save nazmulidris/cbcc3dcd1b968eef6e370d8f5f642b67 to your computer and use it in GitHub Desktop.
snippet showing promise rejection in a test using try and catch
test("test foo", async () => {
function createPromiseThatRejects(): Promise<void> {
return new Promise<void>((_, rejectFn) => {
setTimeout(() => {
rejectFn(new Error("Rejected"))
}, 1_000)
})
}
expect(createPromiseThatRejects()).rejects.toThrow("Rejected")
async function main(): Promise<string> {
try {
await createPromiseThatRejects()
return "ok"
} catch (error) {
return "error"
}
}
expect(await main()).not.toBe("ok")
expect(await main()).toBe("error")
})
test("test if statement to reject or resolve", async () => {
let toReject = true
let reject_count = 0
let resolve_count = 0
function createPromise(): Promise<string> {
return new Promise<string>((resolveFn, rejectFn) => {
setTimeout(() => {
if (toReject) {
reject_count = reject_count + 1
rejectFn(new Error("Rejected")) // 😮 This does not throw error here!
} else {
resolve_count = resolve_count + 1
resolveFn("ok")
}
}, 1_000)
})
}
expect(reject_count).toBe(0)
expect(resolve_count).toBe(0)
const p_1 = createPromise()
try {
const _result = await p_1 // 💣 throws Error!
expect(_result).toBe("ok")
}
catch (e: unknown) {
let error = e as Error
expect(error).toBeInstanceOf(Error)
expect(error.message).toBe("Rejected")
}
expect(reject_count).toBe(1)
expect(resolve_count).toBe(0)
toReject = false
const p_2 = createPromise()
try {
const _result = await p_2 // 💣 may throw Error!
expect(_result).toBe("ok")
} finally { }
expect(reject_count).toBe(1)
expect(resolve_count).toBe(1)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment