Search code examples
node.jsmocha.jses6-modules

Mocha: tests cannot find module


I have a very simple unit test that starts in these lines:

import {SOUTH_EVENTS_ENUM, SouthEventsManager} from "@app/common/south_events_manager";
import {expect} from "chai";
import config from "config";
const {KafkaSouth} = require('@app/kafka_conn/kafka_south');
const sinon = require("sinon");

declare const Tester: any;

describe('SouthEventsManager', function()  {
    const kafkaSouthStub = sinon.createStubInstance(KafkaSouth);
    const southEventsManager = new SouthEventsManager(kafkaSouthStub);

As you can see, the module SouthEventsManager is imported in the test file.

I run Mocha with the following runner: enter image description here

However, I get the error:

Error: Cannot find module '@app/common/south_events_manager' Require stack:

  • C:\HQNorth\North\test\common\south_events_manager.ts

As you can understand, the module SouthEventsManager cannot be found.

Do you have any idea?


Solution

  • Seems like you have configured path aliases in your tsconfig.*.json file. Mocha does not know it, it assumes it is some module (NodeJS one, relative file, or just 3rd party package). You need to tell it. You need to install package tsconfig-paths and change your Mocha running script to:

    mocha -r ts-node/register -r tsconfig-paths/register "test/**/*.ts"