score:2

Accepted answer

there is 02 options

  1. using ts-mocha the short way => npm install --save-dev ts-mocha

mocha thin wrapper that allows running typescript tests with typescript runtime (ts-node) to get rid of compilation complexity. all mocha features are available without any limitation. see documentation.

use this ts configuration for the test tsconfig.testing.json.

{
  "compileroptions": {
      "module": "commonjs",
      "target": "es5"
  },
  "include": ["src/test/*"]
}

this a basic configuration you can update it according to your need

add script to package.json scripts: "test-ts": "ts-mocha -p tsconfig.testing.json src/test/*"

well you should pay attention for importing text files that may run into issues. it will lead to token errors so move them to another files and make sure your utils functoins to be pure functions since you run unit test.

another important note: you should set "module": "commonjs" to fix conflict issues, like yours cannot use import statement outside a module.

  1. use normal mocha with ts-node/register for typescript execution. check the documentation
  • you should install ts-node and cross-env to use the new tsconfig.testing.json.
  • this is a simple configuration for the tsconfig.testing.json. note you should add to the up configuration moduleresolution to node check here for more details. add the path to your declaration types if there is any to avoid errors of type error ts2304: cannot find name "type_name".
  • add script to package.json scripts: cross-env ts_node_project=\"tsconfig.testing.json\" mocha -r ts-node/register src/test/*
{
  "ts-node": {
    "files": true
  },
  "compileroptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleresolution": "node"
  },
  "include": [
    "src"
  ],
  "exclude": [
    "./node_modules/",
    "./dist/"
  ], 
  "files": [
    "path_to_your_types_declaration"
  ]
}

Related Query

More Query from same tag