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?
Oh. How embarrassing...
TS_NODE_PROJECT='src/tsconfig.json' mocha --require ts-node/register src/*_test.ts
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With