mercredi 17 juin 2020

How to run typescript tests as module in node 14?

When running tests nodejs explains that I cannot use import. However according to this answer one should in newer versions of nodejs? nodejs is 14.4.0.

I try to the run the following code with npm run test:

import { expect } from 'chai';
import 'mocha';

describe('Hello function', () => {
    it('should work', () => {
        expect(true).to.equal(true);
    });
});

But this returns the error:

import { expect } from 'chai';
^^^^^^

SyntaxError: Cannot use import statement outside a module

The package.json and tsconfig.json:

{
  "name": "configuration-loader",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "mocha -r ts-node/register test/**/*.test.ts",
    "tsc": "tsc"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@types/node": "^14.0.13",
    "typescript": "^3.9.5"
  },
  "devDependencies": {
    "@types/chai": "^4.2.11",
    "@types/mocha": "^7.0.2",
    "@types/mock-fs": "^4.10.0",
    "chai": "^4.2.0",
    "mocha": "^8.0.1",
    "mock-fs": "^4.12.0",
    "sinon": "^9.0.2",
    "ts-node": "^8.10.2"
  },
  "type": "module"
}

tsconfig.json:

{
  "compilerOptions": {
    "target": "es2019",
    "module": "es2015",
    "lib":  ["es2020"],
    "strict": true,

    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true 
  }
}

Aucun commentaire:

Enregistrer un commentaire