Testing

Running tests with node:test, and what the framework leaves to you

How Tests Run

npm test runs basicben test, which runs Node's built-in test runner, node --test. There is nothing to install. With no arguments it picks up *.test.js, *.test.mjs and *.test.ts files under tests/ and src/; Node 24 strips TypeScript types itself. Tests run with NODE_ENV=test.

npm test

Run every test once

npm test -- tests/posts.test.js

Only the files or globs you name

npm test -- --watch

Re-run on change

npm test -- --coverage

Print a coverage report

test is the only test script in package.json. The arguments after -- are what npm forwards. Files you name replace the default patterns. --watch becomes Node's --watch, --coverage becomes --experimental-test-coverage, and any other flag goes to node --test as it is, so npm test -- --test-name-pattern=login works. npx basicben test does the same without npm.

What the Framework Does Not Provide

There is no testing module. Alongside the package root there are nineteen entry points — server, client, db, auth, validation, content, storage, mail, hooks, rate-limit, etag, webhooks, and the auth/* and storage/* families — and not one of them is for tests. No test client, no request builder, no database reset helper, no model factories.

Less of that is missing than it first appears. Controllers are functions, so call them. Models are objects, so call them. The query builder works against any SQLite file, so a test can have one of its own. The part you do have to arrange yourself is HTTP-level testing: exercising routing and middleware end to end means starting a server and using fetch against it.

A Plain Test

Test files sit next to the code they cover, or under tests/ if you prefer them apart. node:test gives you describe, it, before, after and mock; node:assert/strict does the checking.

src/utils/helpers.test.js
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import { slugify } from './helpers.js'

describe('slugify', () => {
  it('converts text to a slug', () => {
    assert.equal(slugify('Hello World'), 'hello-world')
  })

  it('removes punctuation', () => {
    assert.equal(slugify('Hello! World?'), 'hello-world')
  })
})

Testing a Controller

A controller action is an ordinary async (req, res) function, so a test can call it with objects you build by hand. Only the properties the action actually reads need to exist, which for most actions is body,params and whatever your auth middleware attaches.

tests/PostController.test.js
import { describe, it, mock } from 'node:test'
import assert from 'node:assert/strict'
import { PostController } from '../src/controllers/PostController.js'

// res is whatever the controller calls. json(data, status) is the only
// method these paths use, so a mock function is enough.
function mockRes() {
  return { json: mock.fn() }
}

describe('PostController.store', () => {
  it('returns 422 when the body fails validation', async () => {
    const res = mockRes()

    await PostController.store({ body: { title: 'x' }, userId: 1 }, res)

    assert.equal(res.json.mock.callCount(), 1)
    const [data, status] = res.json.mock.calls[0].arguments
    assert.equal(status, 422)
    assert.ok(data.errors.title)
    assert.ok(data.errors.content)
  })
})

A validation failure returns before any query runs, so this test needs no database at all. Actions that do reach the database need the setup in the next section.

Testing Database Code

Point the connection at a scratch SQLite file before the first query runs, and delete it afterwards. resetDb() drops the cached connection so the next call opens the file you just named, and creating the schema in before keeps each run independent of migration state.

tests/posts.test.js
import { describe, it, before, after } from 'node:test'
import assert from 'node:assert/strict'
import { existsSync, unlinkSync } from 'node:fs'
import { db, query, resetDb } from '@basicbenframework/core/db'

const TEST_DB = './tests/posts.test.sqlite'

function removeTestDb() {
  // WAL mode leaves two sidecar files next to the database.
  for (const suffix of ['', '-wal', '-shm']) {
    if (existsSync(TEST_DB + suffix)) unlinkSync(TEST_DB + suffix)
  }
}

before(async () => {
  removeTestDb()

  // basicben.config.js leaves db.url unset, so DATABASE_URL decides
  // the file. resetDb() clears any connection opened before this.
  process.env.DATABASE_URL = TEST_DB
  resetDb()

  await db.exec(`
    CREATE TABLE posts (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      title TEXT NOT NULL,
      published INTEGER DEFAULT 0
    )
  `)
})

after(async () => {
  await db.close()
  removeTestDb()
})

describe('posts', () => {
  it('inserts a row and reads it back', async () => {
    const result = await (await query('posts'))
      .only('title', 'published')
      .insert({ title: 'Hello', published: 1 })
    const post = await (await query('posts')).find(result.lastInsertRowid)

    assert.equal(post.title, 'Hello')
    assert.equal(post.published, 1)
  })

  it('refuses a write that names no columns', async () => {
    await assert.rejects(
      (await query('posts')).insert({ title: 'Unlisted' }),
      { code: 'MASS_ASSIGNMENT' }
    )
  })

  it('drops columns that only() does not list', async () => {
    await (await query('posts')).only('title').insert({ title: 'Draft', published: 1 })
    const post = await (await query('posts')).where('title', 'Draft').first()

    assert.equal(post.published, 0)
  })

  it('rolls back when the transaction callback throws', async () => {
    await assert.rejects(
      db.transaction(async (tx) => {
        await tx.run('INSERT INTO posts (title) VALUES (?)', ['Rolled back'])
        throw new Error('boom')
      }),
      { message: 'boom' }
    )

    assert.equal(await (await query('posts')).where('title', 'Rolled back').count(), 0)
  })
})

Since 0.9, insert() and update() throw MASS_ASSIGNMENT unless the chain names its columns with only(...), or opts out with unguarded(). Test writes follow the same rule as app code. Raw db.run() and tx.run() are not affected.

Two things to watch. The connection is one cached instance per process, resolved once from db.url in basicben.config.js falling back to DATABASE_URL — the config wins. A project that sets it there will have its tests write to the development database instead, so set the test path in the config or leave db.url unset. And SQLite will not bind JavaScript booleans, so test data uses 1 and 0 like everything else.

Node runs each test file in its own process, several at once. Files that share one SQLite path will collide, so give each file its own database name, or keep database tests in a single file.

Coverage

Coverage is built into Node, so there is no plugin to install. --coverage turns on --experimental-test-coverage and prints a table of line, branch and function coverage after the results. Node's own coverage flags pass straight through.

Coverage, with and without thresholds
npm test -- --coverage
npm test -- --coverage --test-coverage-lines=80

There is no test UI. --ui was a Vitest flag; basicben test prints a warning and ignores it.

Coming From Vitest

Earlier versions of basicben test ran Vitest, which the framework never installed. A file that imports from vitest does not run under node --test, so it has to move over. The change is mostly mechanical.

Vitest to node:test
import { describe, it, expect, vi } from 'vitest'
// becomes
import { describe, it, mock } from 'node:test'
import assert from 'node:assert/strict'

beforeAll / afterAll         →  before / after
expect(a).toBe(b)            →  assert.equal(a, b)
expect(a).toEqual(b)         →  assert.deepEqual(a, b)
expect(a).toBeDefined()      →  assert.ok(a !== undefined)
await expect(p).rejects...   →  await assert.rejects(p, ...)
vi.fn()                      →  mock.fn()

If you would rather keep Vitest, install it and set the test script to vitest run. basicben test will not run it for you.

Practices That Hold Up Here

Give each test its own data

There is no reset helper, so tests that assume an empty table break as soon as another test inserts. Create what you assert on, or assert on rows you inserted by name.

Test the model, not the query builder

The builder has its own tests. What is worth covering is the SQL you wrote by hand, especially the joins the builder cannot express.

Cover validation failures

The 422 path returns before any query, so it is the cheapest test in the suite and the one most likely to regress when a schema changes.

Keep the database out of unit tests

Anything that is a pure function of its arguments should be tested as one. Reserve the SQLite fixture for code that genuinely queries.

Name tests after the behaviour

The name is what you read when it fails, and "returns 422 when the body fails validation" tells you more at that moment than "store works".