TypeScript Node.js testing tips

Situation 1

Use mocha in server-side TypeScript projects with compilerOptions.paths in tsconfig.json ?

Then we need:

  1. mocha
  2. tsconfig-paths
  3. ts-node
  4. { "ts-node": { "files": true } } in the tsconfig.json file (see more here)

Depending on how we import our modules around in the codebase, point (4) above may not always be needed. In one of my projects, it was crucial.

Then run our test with e.g:

mocha --require ts-node/register --require tsconfig-paths/register

So that compilerOptions.paths in our tsconfig.json file is respected.

This way we can test directly against our .ts files

Situation 2

Use jest in server-side TypeScript projects?

  • add { "testEnvironment": "node" } to the config (e.g. the jest entry in package.json or equivalents)
  • <rootDir> token can be used inside moduleDirectories
  • moduleNameMapper can be useful

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s