38

I was watching this video in order to learn how to add some simple tests to my Express routes but I am getting all kind of errors while executing a test. The error is:

import * as chai from 'chai';

^^^^^^

SyntaxError: Cannot use import statement outside a module

I have read some similar Stack Overflow questions and GitHub issues but I didn't find a solution for my own application. Finally I found Mocha documentation on GitHub regarding ES modules but it didn't work:

I created the app using TypeScript and CommonJS module to transpile, so I added "test": "env TS_NODE_COMPILER_OPTIONS='{\"module\": \"commonjs\" }' mocha src/test/*.ts" to the package.json scripts but I am getting the same error every time. I am using ts-node as a server.

Anyway, this is my tsconfig.json file:

{
    "compilerOptions": {
        "sourceMap": true,
        "target": "es6",
        "module": "commonjs",
        "outDir": "./dist",
        "rootDir": "./src"
    },
    "exclude": [
        "node_modules"
    ]
}

And this is the src/test/mi-route.ts file:

import * as chai from 'chai';
import * as chaiHttp from 'chai-http';
import server from '../app';

// Assertions
chai.should();

chai.use(chaiHttp);

describe('API Users', () => {
    // Test Route GET
    describe('GET /api/admin/users', () => {
        it('Should return all the users', done => {
            chai.request(server)
                .get('/api/admin/users')
                .end((err, response) => {
                    response.should.have.status(200);
                    response.body.should.be.a('object');
                    done();
                });
        });
    });
});

An this is my package.json scripts:

"scripts": {
    "dev": "ts-node-dev src/app.ts",
    "start": "node dist/app.js",
    "test": "env TS_NODE_COMPILER_OPTIONS='{\"module\": \"commonjs\" }' mocha src/test/*.ts",
    "build": "tsc -p"
  },

So... any suggestions? Should I change Common JS Module? Thanks in advance

1
  • Maybe you should be using ts-mocha to run your tests instead of mocha? May 1, 2021 at 4:09

6 Answers 6

25

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

2
  • 1
    Comparing my file with the one from the link solved my issue. Thanks! May 29, 2020 at 20:26
  • 1
    I spent over a day pulling my hair out over this. This fixed everything!!!
    – Luke
    Jun 25, 2020 at 20:41
22

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.

2
  • 1
    Worked for me, after I fixed your typo: tsconfig.testing.json, instead of tscconfig.testing.json. Feb 3, 2021 at 15:48
  • You could also have the second file under test dir: test/tsconfig.json
    – peterhil
    Jul 15, 2021 at 19:52
9

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)

1

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"
1
-1

I've recently hit this problem a few times in a project I'm working on.

The project contains many smaller modules which are all written in TypeScript and compiled before being committed. I have (clearly at least couple of times by the fact this link was already purple) somehow managed to commit my module without compiling. This resulted in the error when mocha tried to execute the .js version of a dependency which wasn't committed to version control.

Building the dependency, committing and updating the packages fixed my issue. Hopefully this helps someone else out in a similar position to me!

-1

Another possible cause for this error:

Is you file type .tsx instead of .ts? Changing it to .ts will fix the error or add proper support for .tsx files.

Not the answer you're looking for? Browse other questions tagged or ask your own question.