Mocking es6 with mocha in Typescript

733 Views Asked by At

I am struggling to properly stub/mock unit tests when using es6 modules along with a project with mixed .js and .ts files.

According to this post, testdouble should be able to provide the ESM mocking I need. However, it requires using --loader=testdouble to work, and I am currently using --loader=ts-node/esm. If I attempt to replace ts-node/esm, it is unable to find Typescript files:

Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/Users/repos/my-repo/src/models/connectionModel.js' imported from /Users/repos/my-repo/test/constants.tjs

(connectionModel is ts and imported as .js per esm convention)

Due to project requirements, I would need the project to be compiled in es6+, so removing type: module or setting module: cjs are not viable options for me.

Is there a viable way to use both loaders, or some other viable way to mock with es6?

package.json:

{
  "type": "module",
  "scripts": {
     "test": mocha test/*.js test/*.spec.ts -r dotenv/config
  }
}

tsconfig.json:

{
  "compilerOptions": {
     "target": "es2016",
     "module": "es6,
     "moduleResolution": "node16"
     "allowJs": true,
     "esModuleInterop": true
  },
  "ts-node": {
     "esm": true
  }
  "include": [
     "./src/**/*",
     "test/**/*/.ts",
     "test/**/*.js"
  }
}

.mocharc.json: (grabbing from this answer)

{
   "node-option": [
      "experimental-specifier-resolution=node",
      "loader=ts-node/esm"
   ]
}
0

There are 0 best solutions below