DEV Community

Cover image for Using Node's built-in test runner with Turborepo
Andrej Kirejeŭ
Andrej Kirejeŭ

Posted on

Using Node's built-in test runner with Turborepo

It takes only five easy steps to add unit tests to a Turborepo monorepo. No external testing frameworks, such as Jest or Mocha, are needed.

1. Add tsx at the monorepo’s root level to run TypeScript code without issues related to different module systems:

npm add --dev tsx
Enter fullscreen mode Exit fullscreen mode

2. Add a test task to turbo.json:

{
  ...
  "tasks": {
    "test": {
      "outputs": []
    },
    ...
  },
  ...
}
Enter fullscreen mode Exit fullscreen mode

3. Add a test script in every package.json where necessary:

  "scripts": {
    ...
    "test": "tsx --test"
  },
Enter fullscreen mode Exit fullscreen mode

4. Add a test script into the monorepo's root package.json:

  "scripts": {
   ... 
   "test": "turbo run build && turbo run test"
  }
Enter fullscreen mode Exit fullscreen mode

The build step is optional, but it ensures the project compiles successfully before running tests. Alternatively, add a dependency on the build step in turbo.json.

5. That is it. Now add your first test using the built-in Node.js test runner functionality:

add.ts

  export function add(a: number, b: number) {
    return a + b;
  };
Enter fullscreen mode Exit fullscreen mode

add.test.ts

import assert from 'node:assert/strict';
import { describe, it } from 'node:test';
import { add } from './add.ts';

describe('Test addition', () => {
  it('should add two positive numbers', () => {
    assert.equal(add(2, 2), 4);
  });

  it('should add two negative numbers', () => {
    assert.equal(add(-2, -2), -4);
  });
});
Enter fullscreen mode Exit fullscreen mode

Finally, give it a try by running:

npm run test
Enter fullscreen mode Exit fullscreen mode

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay