Jest: Mocking modules and __mocks__/<module>/index.js

Created on 7 Sep 2017  路  3Comments  路  Source: facebook/jest


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

Potential bug as described behaviour below could be intentional.

What is the current behavior?

If the current behavior is a bug, please provide the steps to reproduce and either a repl.it demo through https://repl.it/languages/jest or a minimal repository on GitHub that we can yarn install and yarn test.

Currently when creating a mock for modules, you can add it to root __mocks__ directory. And it also supports sub-modules like so:

# __mocks__/@module/x.js
// add some mocked implementation

# some.test.js
jest.mock('@module/x');
import x from '@module/x';

However it fails to recognise the same LOAD_INDEX (or even perhaps LOAD_AS_DIRECTORY resolver behaviour as documented in Node.js documentation. For example, this won't work:

# __mocks__/module/index.js
// add some mocked implementation

# some.test.js
jest.mock('module');
import x from 'module';

Couldn't or didn't know how to create a global mock on repl.it so here's a contrived example:

# main.js
import Twilio from 'twilio';
const twilio = new Twilio('x', 'y');

twilio.messages.create({}).then(console.log).catch(console.error);

# __mocks__/twilio/index.js <-- this is the issue
export default class Twilio {
  constructor() {}

  get messsages() {
    return {
      create: async function (options) { console.log(options); }
    }
  }
}

# main.test.js
jest.mock('twilio');

import main from './main';
main();

throws

[TypeError: Cannot read property 'messages' of undefined]

However if I do this it works as expected:

$ mv __mocks__/twilio/index.js __mocks__/twilio.js

What is the expected behavior?

Jest recognises __mocks__/twilio/index.js as module twilio. I understand that the current behaviour could be intentional, in which case we should proceed by documenting it.

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

# package.json
{
  ...,
  "jest": {
    "testEnvironment": "node"
  }
}
Bug Help Wanted

All 3 comments

@hongymagic was it a typo:

  get messsages() {

Just came across this. Still a bug in 23.0.0-charlie.2 unless I'm doing it wrong. I don't suppose you've found a workaround?

Definitely a bug. Dug a bit into it, and the issue is that when the resolver queries the module map for mocks here: https://github.com/facebook/jest/blob/f4f51914d577dc53748f599f3f626dfe3154883e/packages/jest-resolve/src/index.js#L230, the mock is saved as twilio/index here: https://github.com/facebook/jest/blob/f4f51914d577dc53748f599f3f626dfe3154883e/packages/jest-haste-map/src/module_map.js#L58-L60 and not twilio.

I'm not sure how to fix it though. Help welcome!

Was this page helpful?
0 / 5 - 0 ratings