Expect to throw with Typescript using Bun:test - ts(2348)
typescript, bunjs

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
forPromise
it("should return NotFoundError", () => {
expect(getUserData("nonexistentUserId")).rejects.toBeInstanceOf(NotFoundError)
})
Advanced Usage with Custom Error Types
Use
new CustomError()
insteadCustomError
to prevent warningBe 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")
}
}


PreviousAlfred5 icin python ve alfred5 paketi ile Alfred Workflowu GelistirmekNextType Alias Gösterimi Sorunu ve Çözümü
Last updated
Was this helpful?