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

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay