# 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)
