Links
Comment on page

Expect to throw with Typescript using Bun:test * ts(2348)

typescript, bunjs
2731804.png

Basic Example

  • 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()
})

Async Example

  • Use rejects for Promise
it("should return NotFoundError", () => {
expect(getUserData("nonexistentUserId")).rejects.toBeInstanceOf(NotFoundError)
})

Advanced Usage with Custom Error Types

  • Use new CustomError() instead CustomError 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 `() =>`
})

Value of type "typeof X' is not callable. Did you mean to include 'new'? ts(2348)

  • 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
2023 © Yunus Emre AK