bun test: Snapshot Engine, Native Mock Hoisting, and Jest Compatibility
- Last updated
- Prerequisites:
- Jest / Vitest testing basics
- Unit testing and mocking concepts
- bun
- test
- bun-test
- jest
- mocking
- snapshots
- testing
Read at your depth
The practical view
`bun test` is Bun's built-in, Jest-compatible test runner. Run tests with `bun test`. It imports standard `describe`, `it`, `test`, `expect`, `beforeEach`, `afterEach`, and `mock` from `bun:test`. It natively supports TypeScript and JSX out of the box with zero configuration files (`babel.config.js` or `tsconfig.json` test loaders are not required).
The same idea in other frameworks
Jest / Vitest runner running in Node.js.`Deno.test()` with `@std/assert`.`bun test` with `import { test, expect } from 'bun:test'`.Playwright / Cypress browser testing.Legacy vs modern
Jest Configuration Overload vs Zero-Config bun:test
Jest requires multiple npm loaders and config files for TypeScript; `bun test` works out of the box.
npm i -D jest ts-jest @types/jest; // ❌ Complex config and slow startupimport { test, expect, mock } from 'bun:test'; // ✅ NEW: Built-in, zero configInterview gotchas
Context
Interviewers test your knowledge of dependency mocking in Bun.
The mechanical answer
Use `mock.module('module-name', () => { return { myExport: () => 'mocked' }; })`. `mock.module` intercepts the module resolution map inside the JavaScriptCore runtime. Any subsequent import of `'module-name'` throughout the test suite will receive the mocked exports.
Trap
`mock.module` hoists automatically, but to restore original module implementations, call `mock.restore()` or `mock.module()` with the original factory.
Context
Checks knowledge of DOM testing setups in Bun.
The mechanical answer
Yes. You can install `happy-dom` or `jsdom` and configure Bun to use it by creating a preload script: `bun test --preload ./setup-dom.ts` where `setup-dom.ts` attaches `window`, `document`, and DOM globals to `globalThis`.
Trap
Bun does not ship with built-in DOM elements in the runtime core; DOM globals must be provided via `happy-dom` or `jsdom` for React/Vue component tests.