bun test is deeply integrated with Bun’s runtime. This is part of what makes bun test fast and simple to use.
Environment Variables
NODE_ENV
bun test automatically sets $NODE_ENV to "test" unless it’s already set in the environment or via .env files. This is standard behavior for most test runners and helps ensure consistent test behavior.
NODE_ENV explicitly:
terminal
TZ (Timezone)
By default, allbun test runs use UTC (Etc/UTC) as the time zone unless overridden by the TZ environment variable. This ensures consistent date and time behavior across different development environments.
terminal
Test Timeouts
Each test has a default timeout of 5000ms (5 seconds) if not explicitly overridden. Tests that exceed this timeout will fail.Global Timeout
Change the timeout globally with the--timeout flag:
terminal
Per-Test Timeout
Set timeout per test as the third parameter to the test function:Infinite Timeout
Use0 or Infinity to disable timeout:
Error Handling
Unhandled Errors
bun test tracks unhandled promise rejections and errors that occur between tests. If such errors occur, the final exit code will be non-zero (specifically, the count of such errors), even if all tests pass.
This helps catch errors in asynchronous code that might otherwise go unnoticed:
Promise Rejections
Unhandled promise rejections are also caught:Custom Error Handling
You can set up custom error handlers in your test setup:CLI Flags Integration
Several Bun CLI flags can be used withbun test to modify its behavior:
Memory Usage
terminal
Debugging
terminal
Module Loading
terminal
Installation-related Flags
Watch and Hot Reloading
Watch Mode
When runningbun test with the --watch flag, the test runner will watch for file changes and re-run affected tests.
terminal
math.js, only math.test.ts will re-run, not all tests.
Hot Reloading
The--hot flag provides similar functionality but is more aggressive about trying to preserve state between runs:
terminal
--watch is the recommended option as it provides better isolation between test runs.
Global Variables
The following globals are automatically available in test files without importing (though they can be imported frombun:test if preferred):
Process Integration
Exit Codes
bun test uses standard exit codes:
0: All tests passed, no unhandled errors1: Test failures occurred>1: Number of unhandled errors (even if tests passed)
Signal Handling
The test runner properly handles common signals:terminal
Environment Detection
Bun automatically detects certain environments and adjusts behavior:Performance Considerations
Single Process
The test runner runs all tests in a single process by default. This provides:- Faster startup - No need to spawn multiple processes
- Shared memory - Efficient resource usage
- Simple debugging - All tests in one process
- Tests share global state (use lifecycle hooks to clean up)
- One test crash can affect others
- No true parallelization of individual tests
Memory Management
terminal