new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Bun · Test runner · all subjects

core test writing

45 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

setSystemTime function

Use setSystemTime to change the system time in tests. It accepts a Date object. Call setSystemTime(new Date("2020-01-01T00:00:00.000Z")) to set the time, or call setSystemTime() with no arguments to reset to real time.

What system time affects in tests

setSystemTime affects Date.now(), new Date(), and new Intl.DateTimeFormat().format() in tests.

Jest compatibility for fake timers

bun:test supports Jest's useFakeTimers() and useRealTimers() functions. Call jest.useFakeTimers() to enable fake timers and jest.useRealTimers() to restore real time.

Jest's setSystemTime compatibility

bun:test supports jest.setSystemTime() with a Date object, compatible with existing Jest tests.

Date constructor behavior difference from Jest

In bun:test, the Date constructor does not change when useFakeTimers is called. Date remains equal to itself, and Date.now remains equal to itself. This differs from Jest where the Date constructor changes during fake timers.

jest.now() function

When time is mocked with setSystemTime or useFakeTimers, jest.now() returns the current mocked timestamp as a number. For example, when mocked to 2020-01-01T00:00:00.000Z, jest.now() returns 1577836800000.

Reset system time with no arguments

Call setSystemTime() with no arguments to reset the system time back to real time.

Default timezone in bun test

By default, bun test runs in UTC (Etc/UTC timezone).

Set timezone with TZ environment variable

Pass the TZ environment variable to bun test to change the timezone. Example: TZ=America/Los_Angeles bun test

Set timezone at runtime in tests

Set process.env.TZ at runtime within a test to change the timezone. Example: process.env.TZ = "America/Los_Angeles";

Multiple timezone changes at runtime

Unlike Jest, bun:test allows you to change the timezone multiple times at runtime within tests and it will work correctly.

Import setSystemTime from bun:test

Import setSystemTime from "bun:test" to use it in tests.

Import test utilities from bun:test

Import test utilities using `import { expect, test } from "bun:test";` or `import { test, expect, mock } from "bun:test";` or `import { test, expect, jest } from "bun:test";`. The bun:test module provides test, expect, mock, and jest utilities.

Test file naming patterns

The test runner automatically discovers test files matching these patterns: *.test.{js|jsx|ts|tsx|mjs|cjs|mts|cts}, *_test.{js|jsx|ts|tsx|mjs|cjs|mts|cts}, *.spec.{js|jsx|ts|tsx|mjs|cjs|mts|cts}, *_spec.{js|jsx|ts|tsx|mjs|cjs|mts|cts}.

Filter tests by name with --test-name-pattern

Use the `-t` or `--test-name-pattern` flag to filter tests by name: `bun test --test-name-pattern addition` runs all tests or test suites with "addition" in the name.

Jest compatibility in Bun

Bun ships with a Jest-compatible test runner. Bun aims for compatibility with Jest but not everything is implemented. See the compatibility tracking issue at https://github.com/oven-sh/bun/issues/1825.

Run specific test file

To run a specific test file, ensure the path starts with `./` or `/` to distinguish it from a filter name: `bun test ./test/specific-file.test.ts`.

Supported test file extensions

Test files can use extensions: .js, .jsx, .ts, .tsx, .mjs, .cjs, .mts, .cts. These can be combined with naming patterns like *.test.ts, *_test.ts, *.spec.ts, or *_spec.ts.

Default test timeout

Each test has a default timeout of 5000ms (5 seconds). Tests that exceed this timeout will fail.

Global timeout flag

Set a global timeout for all tests using the --timeout flag when running bun test. For example, bun test --timeout 10000 sets a 10 second timeout for all tests.

Per-test timeout as third argument

Set a per-test timeout by passing a number as the third argument to the test function. For example, test("fast test", () => { expect(1 + 1).toBe(2); }, 1000) sets a 1 second timeout for that test.

Disable test timeout with 0 or Infinity

Pass 0 or Infinity as the third argument to the test function to disable the timeout and allow a test to run indefinitely.

Unhandled errors tracked between tests

bun test tracks unhandled promise rejections and errors that occur between tests. If any occur, bun test exits with a non-zero code even when no test failed.

Custom error handlers with process events

Set up custom error handlers for uncaught exceptions and unhandled rejections using process.on("uncaughtException", handler) and process.on("unhandledRejection", handler) in test setup files.

Global test utilities available without import

The following are available globally in test files without importing: test, describe, it, expect, beforeAll, beforeEach, afterAll, afterEach, jest, and vi.

Import test utilities from bun:test

Test utilities can be explicitly imported from bun:test: import { test, it, describe, expect, beforeAll, beforeEach, afterAll, afterEach, jest, vi } from "bun:test".

Import lifecycle hooks from bun:test

Lifecycle hooks (beforeAll, beforeEach, afterEach, afterAll, onTestFinished) are imported from the 'bun:test' module.

Import test utilities from bun:test

Import test utilities from the built-in `bun:test` module. Common imports include: `test`, `describe`, `expect`, `beforeEach`, `afterEach`, `beforeAll`, `afterAll`, and `expectTypeOf`.

Basic test syntax

Define a test using the `test()` function with a test name and callback. Example: `test("2 + 2", () => { expect(2 + 2).toBe(4); });`

Async tests in Bun

Tests can be async by using `async` in the callback. Alternatively, tests can accept a `done` callback parameter to signal completion. If your test function takes a `done` parameter, you must call it or the test will hang.

Test timeout configuration

Specify a per-test timeout in milliseconds by passing a number as the third argument to `test()`. Example: `test("wat", async () => { ... }, 500);` The default timeout is 5000ms (5 seconds). A timeout throws an uncatchable exception to force the test to stop running and fail. Use `jest.setTimeout()` to set timeout at suite level.

test.retry option for flaky tests

Use the `retry` option to automatically retry a flaky test when it fails. The test passes if it succeeds within the specified number of attempts. Example: `test("flaky network request", async () => { ... }, { retry: 3 });`

test.repeats option for stress testing

Use the `repeats` option to run a test multiple times regardless of pass/fail status. The test fails if any iteration fails. `repeats: N` runs the test N+1 times total (1 initial run + N repeats). Example: `test("ensure test is stable", () => { ... }, { repeats: 20 });` runs 21 times total.

Cannot use both retry and repeats on same test

You cannot use both `retry` and `repeats` options on the same test.

Zombie process cleanup on timeout

When a test times out, Bun kills any still-running processes that the test spawned with `Bun.spawn`, `Bun.spawnSync`, or `node:child_process`, and logs a message to the console. This prevents zombie processes from lingering after timed-out tests.

test.skip to skip tests

Use `test.skip()` to skip individual tests. Bun does not run skipped tests.

test.todo for marking unimplemented tests

Use `test.todo()` to mark a test as a todo. Bun does not run these tests. To run todo tests and find any that pass, use `bun test --todo`. Once the code works, Bun reports the test as a failure so you can remove the `.todo` marker.

test.only to run specific tests

Use `test.only()` or `describe.only()` to run a particular test or suite of tests. When `test.only()` is present, only tests marked with `.only()` run. Run with `bun test --only` flag.

test.if for conditional tests

Use `test.if(condition)` to run a test conditionally. The test runs only if the condition is truthy. Use it for tests that should only run on a specific architecture or operating system. Example: `test.if(process.platform === "darwin")("runs on macOS", () => { ... });`

test.skipIf for conditional skipping

Use `test.skipIf(condition)` or `describe.skipIf(condition)` to skip a test or suite based on some condition. The test is skipped when the condition is truthy.

test.todoIf for conditional TODO marking

Use `test.todoIf(condition)` or `describe.todoIf(condition)` to mark a test or suite as TODO conditionally. The choice between `skipIf` and `todoIf` signals intent: "invalid for this target" versus "planned but not implemented yet".

test.failing to track known failing tests

Use `test.failing()` when you know a test is failing but you want to track it and be notified when it starts passing. This inverts the test result: a failing test marked with `.failing()` passes, and a passing test marked with `.failing()` fails with a message that it now passes and should be fixed. Use it to track known bugs you plan to fix later or for test-driven development.

test.each for parametrized tests

Use `test.each()` to run the same test with multiple sets of data. This creates a parametrized test that runs once for each test case provided. Array items are passed as individual arguments; non-array items (objects) are passed as a single argument.

test.each format specifiers

Format specifiers for test titles in test.each: %p (pretty-format), %s (String), %d (Number), %i (Integer), %f (Floating point), %j (JSON), %o (Object), %# (Index of the test case), %% (Single percent sign).

expectTypeOf for type testing

Use `expectTypeOf` for testing TypeScript types, compatible with Vitest. These functions are no-ops at runtime. Run `bunx tsc --noEmit` to verify type checks. Example methods: `toEqualTypeOf()`, `toBeNumber()`, `toBeString()`, `toMatchObjectType()`, `toBeFunction()`, `.parameters.toEqualTypeOf()`, `.returns.toEqualTypeOf()`, `.items.toBeNumber()`, `.resolves.toBeNumber()`.

Give your agent this brain