Skip to content
Advertisement

Mocha + TypeScript: Cannot use import statement outside a module

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:

JavaScript

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

JavaScript

An this is my package.json scripts:

JavaScript

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

Advertisement

Answer

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:

JavaScript

Then I changed my package.json scripts as:

JavaScript

Finally I changed the test file like:

JavaScript

Well, running the tests works now.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement