Home > Mobile >  Typescript with mocha - Cannot use import statement outside a module
Typescript with mocha - Cannot use import statement outside a module

Time:11-23

I'm trying to make a simple test to get to know unit tests using mocha.

Folder Structure

  • node_modules
  • package.json
  • package-lock.json
  • testA.ts
  • testA.spec.ts
  • tsconfig.json

tsconfig.json

{
  "compilerOptions": {    
    "target": "ES2019",    
    "module": "commonjs",
    "rootDir": "./",
    "moduleResolution": "node",
    "allowJs": false,
    "declaration": false,
    "outDir": "./dist",
    "esModuleInterop": false,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "noImplicitAny": false,
    "noImplicitThis": true,
    "alwaysStrict": true,
    "skipLibCheck": true
  },
  "exclude": [
    "node_modules"
  ]
}

package.json

{
  "name": "unittest",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "test": "mocha",
    "build": "rm -rf dist && tsc"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/chai": "^4.2.22",
    "@types/jest": "^27.0.3",
    "@types/mocha": "^9.0.0",
    "@types/sinon": "^10.0.6",
    "chai": "^4.3.4",
    "mocha": "^9.1.3",
    "nyc": "^15.1.0",
    "sinon": "^12.0.1",
    "typescript": "^4.5.2",
    "ts-node": "^10.4.0"
  },
  "mocha": {
    "check-leaks": true,
    "globals": [
      "crypto"
    ],
    "recursive": true,
    "spec": [
      "./*.ts"
    ]
  }
}

testA.spec.ts

import * as chai from 'chai'

const expect = chai.expect

describe('First Test', () => {
  it('should run the test', () => {
    const a = 12
    expect(a).to.be.equal(12)
    
  })
})

When I run npm test, I get the follow error.

/home/user/dev/unitTest/node_modules/@babel/core/src/config/files/index-browser.ts:1 import type { Handler } from "gensync";
^^^^^^

SyntaxError: Cannot use import statement outside a module

Tried everything I could find searching on the internet but still unable to solve this one.

CodePudding user response:

I found the solution. Inside package.json I added the require for mocha:

"devDependencies":{...},
"mocha": {
    "require": [
      "support/ts-node-register.js"
    ],

ts-node-register.js

const tsNode = require('ts-node');
tsNode.register({
  files: true,
});
  • Related