Jest: [BUG] - moduleNameMapper (alias) and jest.mock inconsistency

Created on 19 May 2017  路  6Comments  路  Source: facebook/jest

Do you want to request a feature or report a bug?

Bug.

What is the current behavior?

I have:

  myModule.js
__tests__
  myModule-test.js
myModule.js

I have an alias in the moduelNameMapper that allows me to require my module like lib/myModule.

I write a mock like:

const actualModule = require.requireActual('../myModule');

const myModule = {
  ...actualModule,
  functionToOverride: () => 3,
};

export default myModule;

So I can do:

// This case works, it returns the mock version of myModule
jest.mock("../../lib/myModule");
import * as myModule from "../../lib/myModule";

// Second way works too
jest.mock("lib/myModule");
import * as myModule from "../../lib/myModule";

// Last way (using aliases for both) does not work. It returns the original module instead of the mock:
jest.mock("lib/myModule");
import * as myModule from "lib/myModule";

What is the expected behavior?

Return the same (mocked version) in all the variants described above.

Please provide your exact Jest configuration and mention your Jest, node, yarn/npm version and operating system.

  • Jest: 19.0.0 or 20.0.0
  • node: 6.3.1
  • npm: 3.10.3
  • yarn: 0.22.0

Most helpful comment

This appears to be fixed in the current beta version (21.3.0-beta.8).

All 6 comments

I have the same situation.

I was about to open a bug report as well. From what I understand _shouldMock function returns false from jest-runtime. While resolving the module moduleNameMapper replaces the alias with regex and gets the original file.

It should first replace alias first and then check if it should mock or not.

I created a dummy repository to reproduce the problem, which can be found here

This appears to be fixed in the current beta version (21.3.0-beta.8).

I am facing the same issue with version 23.x is that fixed?

I'm experiencing the same issue with 23.6.0 as well.

I am facing the same issue for 23.6.0. Why this is closed?

Was this page helpful?
0 / 5 - 0 ratings