Search code examples
node.jstypescriptmocha.jsts-node

Change default TypeScript configuration file when run the mocha tests


In the question Overriding tsconfig.json for ts-node in mocha the only reason for the overriding of the TypeScript configuration file was the changing of the module option to commonjs. So all suggested solutions were about how to change the module option to commonjs, not about how to change the TtypeScript configuration.

In my case, I want to change the include option. My repository has Source and Test directories, and I need just to compile the Source.

But if to run mocha tests, it will be the message (with ts-node/esm option):

ts-node is configured to ignore this file.
If you want ts-node to handle this file, consider enabling the "skipIgnore" option or adjusting your "ignore" patterns.

Repro

I created the repro. Initially, it was about TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for D:\XXX\project\node_modules\tsconfig-paths\src\__tests__\config-loader.test.ts error, but first I need to deal with this one.


Solution

  • First fix .mocharc.yaml to get rid of the TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for D:\XXX\project\node_modules\tsconfig-paths\src\__tests__\config-loader.test.ts error. The .mocharc.yaml is including everything with **/*.test.ts and this includes stuff in node_modules too.

    Also, ts-node is being registered twice. One by the register: [ts-node/register] and another one by the loader: ts-node/esm. Just use the latter.

    Here's the fix:

    extension:
      - ts
    
    spec: "Tests/**/*.test.ts"
    
    loader: ts-node/esm
    

    Finally, to use a different tsproject.json for tests with ts-node, set the environment variable TS_NODE_PROJECT to './tsconfig.test.json' and run mocha.