Implement expectTypeOf (#21513)

Fixes #7569 

This adds expectTypeOf, but not the experimental `--typecheck` flag from
vitest. To use it, you need to typecheck manually with `bunx tsc
--noEmit` in addition to `bun test`

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
This commit is contained in:
pfg
2025-08-01 12:11:03 -07:00
committed by GitHub
parent dd68364630
commit 7a31108019
19 changed files with 3299 additions and 1 deletions

View File

@@ -426,6 +426,54 @@ test("exactly two assertions", () => {
This helps ensure all your assertions run, especially in complex async code with multiple code paths.
## Type Testing
Bun includes `expectTypeOf` for testing typescript types, compatible with Vitest.
### expectTypeOf
{% callout %}
**Note** — These functions are no-ops at runtime - you need to run TypeScript separately to verify the type checks.
{% endcallout %}
The `expectTypeOf` function provides type-level assertions that are checked by TypeScript's type checker. **Important**:
To test your types:
1. Write your type assertions using `expectTypeOf`
2. Run `bunx tsc --noEmit` to check that your types are correct
```ts
import { expectTypeOf } from "bun:test";
// Basic type assertions
expectTypeOf<string>().toEqualTypeOf<string>();
expectTypeOf(123).toBeNumber();
expectTypeOf("hello").toBeString();
// Object type matching
expectTypeOf({ a: 1, b: "hello" }).toMatchObjectType<{ a: number }>();
// Function types
function greet(name: string): string {
return `Hello ${name}`;
}
expectTypeOf(greet).toBeFunction();
expectTypeOf(greet).parameters.toEqualTypeOf<[string]>();
expectTypeOf(greet).returns.toEqualTypeOf<string>();
// Array types
expectTypeOf([1, 2, 3]).items.toBeNumber();
// Promise types
expectTypeOf(Promise.resolve(42)).resolves.toBeNumber();
```
For full documentation on expectTypeOf matchers, see the [API Reference](/reference/bun/test/expectTypeOf)
## Matchers
Bun implements the following matchers. Full Jest compatibility is on the roadmap; track progress [here](https://github.com/oven-sh/bun/issues/1825).