Skip to content
jshacks.dev
Node.js

How to Use Bun's Built-In SQLite and Test Runner

Use bun:sqlite for a fast embedded database and bun test for Jest-style tests, including in-memory databases, prepared statements, transactions and mocks.

8 min read
Summarize in AI
Flat illustration of a test run shown as a row of passing dots, with the Node.js, SQLite and Jest logos.

Bun ships a SQLite driver and a test runner inside the runtime, so a small data-backed service needs no better-sqlite3, no Jest and no extra install step. Both are meant to be used together. An in-memory database makes tests fast and isolated, and bun test runs them with a Jest-compatible API. This post covers the bun:sqlite module (opening a database, prepared statements, transactions and typed rows) and then the test runner (describe, test, hooks, mocks and snapshots), ending with a complete example that tests a data layer against a fresh in-memory database. The samples target Bun 1.3. The Bun SQLite reference documents every method used here.

Opening a database

bun:sqlite exports a Database class. Pass a file path to persist data, or the special name :memory: for a database that lives only as long as the object does.

db.tsTypeScript
import { Database } from "bun:sqlite";

export const db = new Database("app.db", { create: true });

db.run(`
  CREATE TABLE IF NOT EXISTS todos (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    title TEXT NOT NULL,
    done INTEGER NOT NULL DEFAULT 0
  )
`);

db.run() executes a statement and returns metadata, with no result rows. It is the right call for schema changes and for writes where you do not need the rows back. The create: true option creates the file when it does not exist. For a read-only connection, pass { readonly: true } instead.

SQLite performs best in write-ahead logging mode when several readers share a file with a writer, so many apps turn it on once at start-up:

TypeScript
db.run("PRAGMA journal_mode = WAL");

Prepared statements

A prepared statement compiles the SQL once and reuses the plan, which is faster and, more importantly, keeps user input out of the SQL text. Create one with db.query() and call it as many times as you need.

todos.tsTypeScript
import { db } from "./db";

const insert = db.query("INSERT INTO todos (title) VALUES ($title)");
const all = db.query("SELECT id, title, done FROM todos ORDER BY id");

insert.run({ $title: "write the post" });
insert.run({ $title: "publish the post" });

console.log(all.all());
Text
[
  { id: 1, title: "write the post", done: 0 },
  { id: 2, title: "publish the post", done: 0 }
]

Named parameters keep the $ prefix in the object keys. Positional parameters with ? work as well, and you pass an array of values to the call. A statement has four main ways to run, and picking the right one avoids needless allocation:

MethodReturns
.run()no rows, a result with changes and lastInsertRowid
.get()the first row, or null
.all()an array of every row
.values()an array of arrays, without column names

Use .get() for lookups by primary key and .all() for lists. An .iterate() method also exists for large result sets, where you want to read one row at a time without building the whole array.

Typed rows

In TypeScript you can tell a statement what a row looks like, and map rows onto a class if that suits your model.

typed.tsTypeScript
import { db } from "./db";

type Todo = { id: number; title: string; done: number };

const byId = db.query<Todo, { $id: number }>(
  "SELECT id, title, done FROM todos WHERE id = $id",
);

const todo = byId.get({ $id: 1 });
console.log(todo?.title);
Text
write the post

The two type arguments are the row type and the parameter type. The compiler then rejects a call with a missing parameter or a misspelled column on the result. Remember that SQLite has no boolean type, so the done column comes back as 0 or 1, and the type says number because that is what is stored.

Transactions

Every statement outside a transaction commits on its own, which is slow when you insert a thousand rows. A transaction groups them into one commit. db.transaction() wraps a function and runs it atomically, rolling back if it throws.

bulk.tsTypeScript
import { db } from "./db";

const insert = db.query("INSERT INTO todos (title) VALUES ($title)");

const insertMany = db.transaction((titles: string[]) => {
  for (const title of titles) insert.run({ $title: title });
  return titles.length;
});

const count = insertMany(["a", "b", "c"]);
console.log(`inserted ${count}`);
Text
inserted 3

If any insert.run throws, for example on a constraint violation, the whole batch is rolled back and the error propagates from insertMany. That all-or-nothing behavior is the reason to use the wrapper instead of writing BEGIN and COMMIT by hand.

The test runner

bun test finds files named *.test.ts, *.test.js, *_test.ts or *.spec.ts and runs them. The API is a close match for Jest, so existing habits carry over: describe, test, expect, beforeEach, afterEach, beforeAll and afterAll all come from the bun:test module.

math.test.tsTypeScript
import { describe, expect, test } from "bun:test";

const add = (a: number, b: number) => a + b;

describe("add", () => {
  test("adds two numbers", () => {
    expect(add(2, 3)).toBe(5);
  });

  test("handles negatives", () => {
    expect(add(-2, -3)).toBe(-5);
  });
});
Text
bun test v1.3.0

math.test.ts:
✓ add > adds two numbers [0.12ms]
✓ add > handles negatives

 2 pass
 0 fail
 2 expect() calls
Ran 2 tests across 1 file. [18.00ms]

The timings vary by machine, and the version line reflects the one installed. Note that there is no compile step and no config file. TypeScript works because Bun transpiles on the fly, and a failing assertion prints a diff of the expected and received values.

Run a single file with bun test math.test.ts, filter by name with -t "negatives", or rerun on changes with --watch. Add --coverage to print a coverage table without installing anything.

A fresh database for every test

The strongest reason to pair the two tools is isolation. An in-memory database costs microseconds to create, so each test can have its own, and no test can corrupt another. Structure the data layer so that it takes a database as an argument.

store.tsTypeScript
import { Database } from "bun:sqlite";

export function createStore(db: Database) {
  db.run(`
    CREATE TABLE IF NOT EXISTS todos (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      title TEXT NOT NULL,
      done INTEGER NOT NULL DEFAULT 0
    )
  `);

  const insert = db.query("INSERT INTO todos (title) VALUES ($title)");
  const complete = db.query("UPDATE todos SET done = 1 WHERE id = $id");
  const open = db.query("SELECT title FROM todos WHERE done = 0 ORDER BY id");

  return {
    add: (title: string) => Number(insert.run({ $title: title }).lastInsertRowid),
    complete: (id: number) => complete.run({ $id: id }).changes,
    open: () => open.all().map((row: any) => row.title as string),
  };
}
store.test.tsTypeScript
import { beforeEach, describe, expect, test } from "bun:test";
import { Database } from "bun:sqlite";
import { createStore } from "./store";

let store: ReturnType<typeof createStore>;

beforeEach(() => {
  store = createStore(new Database(":memory:"));
});

describe("todo store", () => {
  test("lists open items in insertion order", () => {
    store.add("first");
    store.add("second");
    expect(store.open()).toEqual(["first", "second"]);
  });

  test("completing an item removes it from the open list", () => {
    const id = store.add("first");
    store.add("second");
    expect(store.complete(id)).toBe(1);
    expect(store.open()).toEqual(["second"]);
  });

  test("completing an unknown id changes nothing", () => {
    expect(store.complete(999)).toBe(0);
  });
});
Text
store.test.ts:
✓ todo store > lists open items in insertion order
✓ todo store > completing an item removes it from the open list
✓ todo store > completing an unknown id changes nothing

 3 pass
 0 fail
 4 expect() calls

beforeEach builds a new :memory: database and a new store before every test, so the second test never sees the rows from the first. Because the schema runs inside createStore, there is no separate migration step to forget.

Mocks and snapshots

The runner includes mocking helpers that mirror Jest. mock() creates a function that records its calls, and spyOn() wraps an existing method.

notify.test.tsTypeScript
import { expect, mock, test } from "bun:test";

function finish(id: number, notify: (message: string) => void) {
  notify(`todo ${id} done`);
}

test("notifies once with the id", () => {
  const notify = mock((message: string) => {});
  finish(7, notify);
  expect(notify).toHaveBeenCalledTimes(1);
  expect(notify).toHaveBeenCalledWith("todo 7 done");
});
Text
✓ notifies once with the id

 1 pass
 0 fail
 2 expect() calls

Snapshot tests work with expect(value).toMatchSnapshot(), and the first run writes a __snapshots__ folder next to the test. Review those files in pull requests like any other code, because an unreviewed snapshot only records whatever the code did that day.

Where this stops

bun:sqlite works only on Bun. Code that imports it will not load on Node.js or Deno, so keep the database access behind a small module if portability matters. Node.js has its own node:sqlite with a similar shape, and the differences are mostly in method names, so a wrapper of a few functions bridges them. Also remember that SQLite allows one writer at a time. For a single-process service that is no problem, and for several processes writing to the same file, set a busy timeout with PRAGMA busy_timeout = 5000 so a writer waits instead of failing at once.

Habits that keep the database healthy

A few small habits save trouble once the app grows past a demo. Turn on foreign key enforcement explicitly with PRAGMA foreign_keys = ON, because SQLite leaves it off by default for historical reasons, and a missing constraint check is a quiet way to store orphaned rows. Keep schema changes in numbered migration functions and record the applied number in PRAGMA user_version, which is a free integer slot in every database file. At start-up, read that number, run any migrations above it inside one transaction and write the new number at the end. A crash halfway then leaves the file at the old version, not in a state nobody can describe.

Close the database when the process ends. Bun closes open handles on exit, but an explicit db.close() in a shutdown handler makes the intent clear and flushes the write-ahead log cleanly, which matters if you copy the file as a backup straight afterwards. For backups of a live database, prefer the SQL statement VACUUM INTO 'backup.db', which writes a consistent copy while the app keeps running, over copying the file with cp, which can catch it mid-write.

In tests, resist the urge to share one database across files for speed. Creating a :memory: database takes well under a millisecond, and a shared one reintroduces the ordering bugs that isolated tests exist to prevent. If a test needs seed data, write a small helper that inserts it through the same store functions the application uses, so the test also exercises the real write path.

Also inTesting
Share

Keep reading

Flat illustration of jobs on a conveyor heading to a rack of workers, with the Node.js, JavaScript, Apache Kafka, Redis and RabbitMQ logos.
Node.js

The Node.js Event Loop Phases Explained

Learn the six phases of the Node.js event loop, where timers, I/O, setImmediate, process.nextTick and promises run, and why their order sometimes surprises you.

6 min read
Flat illustration of jobs on a conveyor heading to a rack of workers, with the Node.js, RabbitMQ, Apache Kafka, Redis and npm logos.
Node.js

What Is Node.js, and What Is It Good At?

Node.js runs JavaScript outside the browser on the V8 engine. Learn what it is, how its event loop works, where it shines, and where another tool fits better.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.