Skip to content

Testing ​

Use tsx to run TypeScript tests with the Node.js built-in test runner. Node.js provides the test API, assertions, reporting, and test execution; tsx adds TypeScript loading.

You need tsx installed in your project and Node.js test runner support.

Run a TypeScript test ​

Create this file in your project directory:

sum.test.ts

ts
import assert from 'node:assert/strict'
import { test } from 'node:test'

test('adds two numbers', () => {
    const result: number = 1 + 2
    assert.equal(result, 3)
})

Run the test from the same directory:

sh
npx tsx --test --test-reporter=tap ./sum.test.ts

The command exits successfully. Stable TAP output excerpt:

text
# tests 1
# suites 0
# pass 1
# fail 0

A failing assertion makes the test fail and the command exit with a nonzero status.

tsx executes tests without type checking them. Run TypeScript type checking separately to check types in your tests and application code.

Discover test files ​

Automatic discovery can select the wrong files

The discovery glob can miss hyphenated test names and include unintended names. Select test files explicitly until the discovery issue is resolved.

Pass explicit test file paths, as in the example above, to select the files you want to run. When you omit paths, tsx supplies the following glob on Node.js versions with test glob support:

text
**/{test,test/**/*,test-*,*[.-_]test}.?(c|m)@(t|j)s

Node.js interprets this glob from the working directory using its own glob matching. Until the issue is resolved, use the explicit-file command above rather than relying on this pattern to select your tests.

Configure the test runner ​

Place Node.js test runner options before the test file paths. The examples use --test-reporter=tap to select the TAP reporter.

Argument or optionTypeDefaultBehavior
Test file pathsStringsOmittedSelect files explicitly; when omitted, use discovery as described above.
--testBooleanfalseRun Node.js's test runner instead of executing a single script.
--test-reporter <name>StringSelected by Node.jsChoose the output reporter, such as tap.

Use the Node.js test runner documentation to find options supported by your Node.js version, including filtering tests and configuring concurrency.