16

I'm having an issue with running mocha when using the paths + baseUrl configuration in TypeScript

My tsconfig.js is set like so:

"baseUrl": "./src/", /* Base directory to resolve non-absolute module names. */
"paths": {
  "interfaces/*": [
    "interfaces/*"
  ],
  "models/*": [
    "models/*"
  ],
  "schemas/*": [
    "schemas/*"
  ],
  "classes/*": [
    "classes/*"
  ],
  "libs/*": [
    "libs/*"
  ],
  "config/*": [
    "config/*"
  ]

and I'm runnings mocha as "mocha build/test"

The compiled TS code fails to find my references since it compiles to

var user_1 = require("interfaces/user");

and if I add "../" beforehand it will compile without problems

Any ideas what I'm doing wrong here?

4 Answers 4

23

You can use tsconfig-paths, follow the instructions on tsconfig-paths:

mocha -r ts-node/register -r tsconfig-paths/register "test/**/*.ts"
Sign up to request clarification or add additional context in comments.

1 Comment

For non-ts-node, the command may just be as simple as mocha -r tsconfig-paths/register, since I think test/**/*.ts is the default behavior.
3

You should use a mocha-TypeScript integration package, such as ts-mocha

Comments

2

In case you are using ts-mocha, it's using the tsconfig-paths package under the hood to resolve with the tsconfig paths but you have to enable it: TS_CONFIG_PATHS=true.

See the official documentation here: https://github.com/piotrwitek/ts-mocha#--programmatic-usage

Comments

0

You should use a normal testing integration package (most popular one). such as moch-typescript. With that you only need to setup in test in package.json

script: 'mocha --ui mocha-typescript test.ts'

https://www.npmjs.com/package/mocha-typescript

I will give you a better example - test.ts

import { suite, test, slow, timeout } from "mocha-typescript";
@suite class Hello {
    @test world() {
        assert.equal(1, 2, "Expected one to equal two.");
    }
}

1 Comment

mocha-typescript is now deprecated, try the package mentioned in Eliran Pe'er's answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.