Running TypeScript Tests With The Node Native Test Runner

Today, I had to setup testing for a TypeScript project. I opted to use Node's native test runner. Getting it working with TypeScript is pretty straightforward.

Install Dependencies

With yarn:
yarn add --dev typescript ts-node

With npm:
npm install --save-dev typescript ts-node

Add Test Command

Create a test command in your package.json

{
  "name": "my-fun-project"
  "version": "1.0.0",
  "scripts": {
    "test": "node --require ts-node/register --test **/*.test.ts"
  },
  "devDependencies": {
    "typescript": "^5.0.0",
    "ts-node": "^10.0.0"
  }
}

And that's it. You can now run all test files ending in *.test.ts by running either yarn test or npm test.

Running an example test

Here's an example test we'll run.

src/index.test.ts

import { test } from 'node:test';
import assert from 'assert';

test('everything is good', () => {
  assert.equal(1, 1);
})

Running via the test command

yarn test
$ node --require ts-node/register --test **/*.test.ts
✔ everything is good (0.75161ms)