> ## Documentation Index
> Fetch the complete documentation index at: https://bun.ll1025.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# 从 Jest 迁移到 Bun 的测试运行器

在许多情况下，Bun 的测试运行器无需修改代码即可运行 Jest 测试套件。运行 `bun test` 代替 `npx jest` 或 `yarn test`。

```sh terminal icon="terminal" theme={null}
npx jest # [!code --]
yarn test # [!code --]
bun test # [!code ++]
```

***

你的测试文件通常可以直接使用。

* Bun 内部将 `@jest/globals` 的导入重写为对应的 `bun:test` 等效项。
* 如果你依赖 Jest 注入 `test` 和 `expect` 等全局变量，Bun 也会这样做。

如果你更愿意直接从 `bun:test` 导入，请更新导入语句。

```ts title="test.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
import { test, expect } from "@jest/globals"; // [!code --]
import { test, expect } from "bun:test"; // [!code ++]
```

***

自 Bun v1.2.19 起，一个三斜线指令可以为全局测试函数启用 **TypeScript 支持**。将其添加到项目中的*一个文件*中，例如：

* 项目根目录中的 `global.d.ts` 文件
* 测试 `preload.ts` 设置文件（如果在 `bunfig.toml` 中使用 `preload`）
* TypeScript 编译包含的任何单个 `.ts` 文件

```ts title="global.d.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
/// <reference types="bun-types/test-globals" />
```

***

添加后，项目中的每个测试文件都将获得 Jest 全局变量的 TypeScript 支持：

```ts math.test.ts icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
describe("我的测试套件", () => {
  test("应该正常工作", () => {
    expect(1 + 1).toBe(2);
  });

  beforeAll(() => {
    // 设置代码
  });

  afterEach(() => {
    // 清理代码
  });
});
```

***

Bun 实现了 Jest 的大部分匹配器，但兼容性并非 100%。请参见 [编写测试](/test/writing-tests#matchers) 中的兼容性表格。

***

如果你使用 `testEnvironment: "jsdom"` 在类似浏览器的环境中运行测试，请按照 [使用 Bun 和 happy-dom 进行 DOM 测试](/guides/test/happy-dom) 指南将浏览器 API 注入到全局作用域中。该指南使用 [`happy-dom`](https://github.com/capricorn86/happy-dom)，它是 [`jsdom`](https://github.com/jsdom/jsdom) 的更轻量和更快的替代品。

```toml bunfig.toml icon="settings" theme={null}
[test]
preload = ["./happy-dom.ts"]
```

***

将 Jest 配置中的 `bail` 替换为 `--bail` CLI 标志。

```sh terminal icon="terminal" theme={null}
bun test --bail=3
```

***

将 `collectCoverage` 替换为 `--coverage` CLI 标志。

```sh terminal icon="terminal" theme={null}
bun test --coverage
```

***

将 `testTimeout` 替换为 `--timeout` CLI 标志。

```sh terminal icon="terminal" theme={null}
bun test --timeout 10000
```

***

许多其他 Jest 设置在 `bun test` 中不适用。

* `transform` — Bun 支持 TypeScript 和 JSX。使用 [插件](/runtime/plugins) 配置其他文件类型。
* `extensionsToTreatAsEsm`
* `haste` — Bun 使用自己的内部源码映射
* `watchman`、`watchPlugins`、`watchPathIgnorePatterns` — 使用 `--watch` 在监听模式下运行测试
* `verbose` — 在 [`bunfig.toml`](/runtime/bunfig#loglevel) 中设置 `logLevel: "debug"`

***

此处未提及的设置不受支持或没有等效项。如果缺少你需要的内容，请[提交功能请求](https://github.com/oven-sh/bun)。

***

参见：

* [将测试标记为待办](/guides/test/todo-tests)
* [编写测试](/test/writing-tests)
