Mocha + TypeScript: Cannot use import statement outside a module
Had the same issue and almost gave up using Mocha with TypeScript (in our case Angular 9).
This is what helped me:
In tsconfig.json
:
Replaced this:
"module": "esnext",
with this:
"module": "commonjs",
Also here I found a working example of Mocha with TypeScript and used the tsconfig
file from there to compare with mine:
https://medium.com/@RupaniChirag/writing-unit-tests-in-typescript-d4719b8a0a40
Also had this problem and found I didn't have to switch to commonJS, just had to enable ESM:
npm install --save-dev esm
./node_modules/mocha/bin/mocha -r esm -r ts-node/register "src/**/*Test.ts"
I was able to test thanks to the @types/chai-http – Can't use ES6 import GitHub issue's answer.
I added a second TypeScript configuration file tsconfig.testing.json
with the following information:
{
"compilerOptions": {
"module": "commonjs",
"target": "es2015",
"lib": ["es2017"],
"declaration": false,
"noImplicitAny": false,
"removeComments": true,
"inlineSourceMap": true,
"moduleResolution": "node"
},
"include": ["scripts/**/*.ts", "src/**/*.ts", "node_modules/lodash-es/**/*.js"]
}
Then I changed my package.json
scripts as:
"test": "env TS_NODE_PROJECT=\"tsconfig.testing.json\" mocha --require ts-node/register 'src/test/**/*.ts'",
Finally I changed the test file like:
import * as chai from 'chai';
import 'chai-http';
import server from '../app';
// Assertions
chai.should();
chai.use(require('chai-http'));
Well, running the tests works now.
Ensure you have .mocharc.json
in your project:
{
"extension": ["ts"],
"timeout": 5000,
"exit": true,
"require": "ts-node/register"
}
(see also https://github.com/mochajs/mocha-examples/tree/master/packages/typescript#es-modules)