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

![2731804.png](https://i.imgur.com/1gYhX55.png)

## Basic Example

* Be careful on `() =>`

```javascript
// 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`

```typescript
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 `() =>`

```javascript
// 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()`

```javascript
export class AlreadyAdjusted extends Error {
	constructor() {
		super("Already adjusted")
	}
}
```

![jRe9NPT.png](https://i.imgur.com/jRe9NPT.png)

![6tNPvSi.png](https://i.imgur.com/6tNPvSi.png)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.yemreak.com/arsiv/programming/expect-to-throw-with-typescript-using-buntest---ts2348.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
