Migrate from Jest to Bun's test runner
In many cases, Bun's test runner can run Jest test suites with no code changes. Run bun test instead of npx jest or yarn test.
npx jest
yarn test
bun test Your test files usually work as-is.
- Bun internally rewrites imports from
@jest/globalsto theirbun:testequivalents. - If you rely on Jest to inject globals like
testandexpect, Bun does that too.
If you'd rather import from bun:test directly, update the imports.
import { test, expect } from "@jest/globals";
import { test, expect } from "bun:test"; Since Bun v1.2.19, a triple-slash directive enables TypeScript support for global test functions. Add it to one file in your project, such as:
- A
global.d.tsfile in your project root - Your test
preload.tssetup file (if usingpreloadin bunfig.toml) - Any single
.tsfile that TypeScript includes in your compilation
/// <reference types="bun-types/test-globals" />Once added, every test file in your project gets TypeScript support for the Jest globals:
describe("my test suite", () => {
test("should work", () => {
expect(1 + 1).toBe(2);
});
beforeAll(() => {
// setup code
});
afterEach(() => {
// cleanup code
});
});Bun implements most of Jest's matchers, but compatibility isn't 100%. See the compatibility table in Writing tests.
If you use testEnvironment: "jsdom" to run your tests in a browser-like environment, follow the DOM testing with Bun and happy-dom guide to inject browser APIs into the global scope. That guide uses happy-dom, a leaner and faster alternative to jsdom.
[test]
preload = ["./happydom.ts"]Replace bail in your Jest config with the --bail CLI flag.
bun test --bail=3Replace collectCoverage with the --coverage CLI flag.
bun test --coverageReplace testTimeout with the --timeout CLI flag.
bun test --timeout 10000Many other Jest settings are irrelevant in bun test.
transform— Bun supports TypeScript & JSX. Configure other file types with plugins.extensionsToTreatAsEsmhaste— Bun uses its own module resolverwatchman,watchPlugins,watchPathIgnorePatterns— use--watchto run tests in watch modeverbose—bun testreports each test by default. Use--only-failuresor--dotsfor less output (see Test reporters).
Many other settings have an equivalent in the [test] section of bunfig.toml. For example:
setupFiles/setupFilesAfterEnv→preloadtestPathIgnorePatterns→pathIgnorePatternsrootDir→rootcoverageDirectory→coverageDircoverageReporters→coverageReportercoverageThreshold→coverageThreshold(as a fraction like0.9, not a percentage)
See Test configuration. Settings without an equivalent are not supported. File a feature request if something you need is missing.
See also: