Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TS-Node with Mocha doesn't use TS_NODE_PROJECT

I'm having trouble with using the env variable TS_NODE_PROJECT when ts-node is used for testing using Mocha.

The project structure looks like this:

src/
  main_test.ts
  tsconfig.json
package.json

In my test, I want to use an async function, which requires "lib": ["es2018"] as a compilation option.

// src/main_test.ts
describe('', () => {
    it('test', () => {
        (async function() {})()
    });
});

// src/tsconfig.json
{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es5",
    "sourceMap": true,
    "lib": ["es2018"]
  },
  "exclude": [
    "../node_modules"
  ]
}

To run the test, I use this command, but it results in an error:

TS_NODE_PROJECT='src' && mocha --require ts-node/register src/*_test.ts
# TSError: ⨯ Unable to compile TypeScript:
# error TS2468: Cannot find global value 'Promise'.
# src/main_test.ts(3,10): error TS2705: An async function or method in ES5/ES3 requires the 'Promise' constructor.  Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option.

This means that src/tsconfig.json is not used. According to Overriding `tsconfig.json` for ts-node in mocha and the ts-node documentation, the command should pass the correct tsconfig.json path to ts-node.

Moving src/tsconfig.json to project directory and running the same command causes the test to succeed. How can I pass the tsconfig.json path to ts-node so that the test compiles correctly?

like image 678
MakotoE Avatar asked Mar 05 '23 14:03

MakotoE


2 Answers

Oh. How embarrassing...

TS_NODE_PROJECT='src/tsconfig.json' mocha --require ts-node/register src/*_test.ts
like image 50
MakotoE Avatar answered Mar 15 '23 17:03

MakotoE


I find very useful to move mocha setup in different files so package.json remains clean, you can use a mocharc file like this:

module.exports = {
  ignore: [
    './test/helpers/**/*',
    './test/mocha.env.js'
  ],
  require: [
    'test/mocha.env', // init env here
    'ts-node/register'
  ],
  extension: [
    'ts'
  ]
}

and then create the file test/mocha.env.js (or call it as you wish) with this content:

process.env.NODE_ENV = 'test'
process.env.TS_NODE_PROJECT = 'src/tsconfig.json'
like image 37
Luca Faggianelli Avatar answered Mar 15 '23 15:03

Luca Faggianelli