How to Run Typescript Tests With Nodejs Test Runner
Pre-requirement
(Installing the correct version of nodejs)
In order to run Typescript tests with nodejs test runner as described in this tutorial, you need to have nodejs v22.6.0+
. If you dont want to install a different version of nodejs to break your other projects, you can install this version via nvm only into this project by running: nvm install v22.7.0
(- this is a current version at the time writing of this blog post), and creating .nvmrc
file with following content
v22.7.0
- Since v21 nodejs supports glob patterns which we need for executing all test files in codebase.
- Since v22.6 nodejs supports native typescript. More about it here: The Easier Way To Setup Nodejs App Written in Typescrips - 5 Steps Needed#^b5567d
Installing Dependencies
The one and only dependency we need is TypeScript Execute (tsx) | tsx. Which can we easily add via command:
yarn add --dev tsx
# replace "yarn" with any package manager you use
Setup Command to Run Tests
Adjust your package.json
file to add the command test
:
{
...
"scripts": {
"test": "node --import tsx --test 'src/**/__tests__/*.spec.ts'"
},
}
This command expects to load and execute test files inside src
, and part of __tests__
folder. You can adjust this glob pattern to your liking.
Creating First Test
import assert from 'assert/strict'
import { describe, it } from 'node:test'
describe('bogus tests', () => {
it('passes', () => {
assert.ok(true)
})
})
Nodejs test runner is super easy, and follows the testing conventions of any other runner.
Running Tests
With this simple yarn command, all tests located in your codebase will be executed 🎉:
yarn test
Producing the following result:
And this is it! Easy right?
This article was originally published on https://craftengineer.com/. It was written by a human and polished using grammar tools for clarity.
Follow me on X (Formally, Twitter) or Bluesky.