Test, build, and ship

Write tests with bun:test

Create fast TypeScript tests with Bun's built-in test runner and use focused assertions to describe behavior.

Bun includes a test runner. You do not need to install Jest or another test package to start.

Create title.ts:

export function normalizeTitle(title: string) {
  return title.trim().replaceAll(/\s+/g, ' ')
}

Create title.test.ts beside it:

import { expect, test } from 'bun:test'
import { normalizeTitle } from './title'

test('normalizes whitespace in a note title', () => {
  expect(normalizeTitle('  Learn   Bun  ')).toBe('Learn Bun')
})

Run every discovered test:

bun test

Bun finds files with names such as .test.ts, _test.ts, .spec.ts, and _spec.ts.

The test has three small parts:

  1. provide an input
  2. call the function
  3. compare the result with the expected value

Add an edge case:

test('keeps a title that is already clean', () => {
  expect(normalizeTitle('Build the API')).toBe('Build the API')
})

Run tests whenever files change:

bun test --watch

You can also generate a coverage report:

bun test --coverage

Coverage tells you which code executed. It does not tell you whether the assertions describe the right behavior. Prefer a few meaningful cases over many tests that only repeat the implementation.

Lesson completed

Take this course offline

Get every free book, course edition, and software download.

Get the download library →