Get rid of Jest/Mocha with TestRunner!

SianLoong
3 min readMar 18, 2023

What’s the common way to run a test in JavaScript? Normally, we install Jest and run the test right? So how can we install and set up Jest for our JavaScript project?

How to set up Jest?

According to the documentation, we need to run npm i -D jest. If we want the type hint, probably we install the Jest typing packagenpm i -D @types/jest .

Install Jest

But what if we need to run the test files written in TypeScript? According to Jest documentation, there are few ways to do it.

Install packages to enable Jest to support TypeScript files

You know what, I’m not going to show you the whole steps of how to set up Jest with TypeScript in this article. I personally feel the setup is kinda frustrating, especially for the developers.

By the way, do you know that starting from NodeJS 18, the standard testing tool (Test Runner) is included by default? But how? Let’s dig in together.

Test Runner available since Nodejs 18

How to set up Test Runner?

1. Install Nodejs ^18

For using Test Runner, you don’t need to install anything except a NodeJS (at least version 18) on your machine.

2. Write tests and run it

  • Write your test file with the suffix of .test.js or .test.ts
  • Use node:test package to define your test scope
  • Use node:assert to check or compare the result

For advance usage, you may refer to the official documentation instead.

sum.test.js (Path: src/sum.test.js)

3. Execute the test command

Remember to pass in the — test option, this is to inform NodeJS to run the test files.

node --test ./src/sum.test.js

4. Hola, observe the result

After the execution is finished, it will show the result.

Apart from that, Test Runner does support asynchronous function tests as well.

Async function tests

OK, this was good, but what if our testing files are written in TypeScript, is Test Runner ready for it or yet?? The answer is YES! I follow the guide on https://github.com/nodejs/help/issues/3902 and it works perfectly.

How to run Test Runner with TypeScript files?

1. Install an NPM package

This package will be used as a loader in Node.

npm i -D tsx

2. Write your test in TypeScript.

sum.test.ts (Path: src/sum.test.ts)

3. Execute the test command

node --loader tsx --test ./src/*test.ts

4. Hola, observe the result

The JavaScript ecosystem is becoming more mature than before, now we have Test Runner to replace Jest/Mocha, and soon we will have typing in JavaScript to replace TypeScript. Let’s get rid of the legacy by migrating today!

--

--

SianLoong

Frontend most of the time. Sometime backend. Sometime low-level.