Comment on page
Expect to throw with Typescript using Bun:test * ts(2348)
typescript, bunjs

2731804.png
- Be careful on
() =>
// someFunction.ts
export function someFunction(shouldThrow: boolean): void {
if (shouldThrow) {
throw new Error("I am an error!")
}
}
// someFunction.test.ts
import { someFunction } from "./someFunction"
test("should throw an error", () => {
expect(() => someFunction(true)).toThrow("I am an error!")
})
test("should not throw an error", () => {
expect(() => someFunction(false)).not.toThrow()
})
- Use
rejects
forPromise
it("should return NotFoundError", () => {
expect(getUserData("nonexistentUserId")).rejects.toBeInstanceOf(NotFoundError)
})
- Use
new CustomError()
insteadCustomError
to prevent warning - Be careful on
() =>
// CustomError.ts
export class CustomError extends Error {
constructor(message: string) {
super(message)
Object.setPrototypeOf(this, CustomError.prototype)
}
}
// someFunction.ts
import { CustomError } from "./CustomError"
export function someFunction(shouldThrow: boolean): void {
if (shouldThrow) {
throw new CustomError("I am a custom error!")
}
}
// someFunction.test.ts
import { someFunction } from "./someFunction"
import { CustomError } from "./CustomError"
test("should throw a custom error", () => {
expect(() => someFunction(true)).toThrow(new CustomError())
// Use `new CustomError()` instead `CustomError` to prevent warning
// Be careful on `() =>`
})
- To prevent the error shown (it can run as expected) use
new AlreadyAdjusted()
export class AlreadyAdjusted extends Error {
constructor() {
super("Already adjusted")
}
}

jRe9NPT.png

6tNPvSi.png