patterntypescriptTip
Bun test runner: built-in Jest-compatible testing
Viewed 0 times
bun testtest runnerjest compatibledescribeexpectmockbun testing
bun
Problem
Running tests in a Bun project without installing Jest or Vitest, while using a familiar assertion API.
Solution
Use bun test — it discovers *.test.ts files and runs them. The API mirrors Jest: describe, it/test, expect, beforeEach, afterEach, mock. No config needed for basic test suites.
Why
Bun's built-in test runner avoids the cold start of loading Jest's heavy module graph. Tests run significantly faster, especially in large projects.
Gotchas
- Not 100% Jest API compatible — some Jest-specific matchers or mocking patterns may not work
- Snapshot testing is supported but snapshot files are stored differently than Jest
- bun test --watch re-runs on file changes; useful for TDD
- Coverage requires --coverage flag and generates lcov output; HTML reports need a separate tool
Code Snippets
Test file using bun:test
import { describe, it, expect, mock } from 'bun:test';
describe('add', () => {
it('adds two numbers', () => {
expect(1 + 2).toBe(3);
});
it('handles mocks', () => {
const fn = mock(() => 42);
expect(fn()).toBe(42);
expect(fn).toHaveBeenCalledTimes(1);
});
});Revisions (0)
No revisions yet.