'How to mock a module in compiled code with path mapping?

I use path mapping extensively in my source. I also use the typescript-transform-paths plugin and the ttypescript compiler to resolve mapped paths to relative paths during compilation. I have also configured some tests using Jest. There are two scripts - one runs tests in "development mode" using ts-jest, while another one runs jest against the compiled (production) code. Normally it all works just fine, I was able to use source maps to generate proper coverage reports when testing compiled code.

However, problem presents itself when I use try to mock an aliased (path-mapped) module. Here's a part of the test:

jest.mock("@config");

import "@config";

I have also setup Jest to use a moduleNameMapper. In jest.config.js:

module.exports = {
  moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, { prefix: "<rootDir>/" })
}

There is also a mock file at __mocks__/@config.

This setup works correctly when run using ts-jest - Jest picks up my mock and imports it where @config is required.

Unfortunately, I don't know how to get it to work with compiled code. This is basically what the compiled code looks like:

// This statement did not change, obviously, because this is not an import
jest.mock("@config");

// However, the aliased module name is resolved to a relative path here
require("../../config");

So Jest is mocking @config, but I am actually importing something else and the mock does not work.

I have tried to get it to work using different moduleNameMapper configurations, but nothing helped, unless I use this fragile hack:

module.exports = {
  moduleNameMapper: {
    "^(../)*config$": "<rootDir>/dist/test/__mocks__/@config"
  }
}

This makes jest.mock("@config") redundant.

How can I properly solve this?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source