jest icon indicating copy to clipboard operation
jest copied to clipboard

Automocker `__mocks__/` discovery should support node modules with `@namespace/module` naming.

Open sterpe opened this issue 11 years ago • 6 comments

I'm having a hard time getting the autoMocker to find manual mocks in the __mocks__/ folder when the module name includes a @namespaces, e.g. require('@quux/foo');

Tried this:

__mocks__/
  @quux/
     foo.js

&&

__mocks__/
  foo.js

Right now I've ended up using setMock('@quux/foo', mockInstance) and pulling in mockInstance with require.requireActual but it seems less than ideal.

Other ideas? Or will this be supported in 0.5.x?

sterpe avatar Aug 15 '15 16:08 sterpe

I recommend using jest.mock('@namespace/module/name', () => {…}) for this. I don't think we'll add support for nested mocks.

cpojer avatar Sep 29 '16 08:09 cpojer

I have a similar issue with importing modules from Braintree - in my code I'm importing modules from 'braintree-web/client', 'braintree-web/hosted-fields', 'braintree-web/data-collector', and 'braintree-web/paypal', and my mocks for these objects are non-trivial, so to rely on jest.mock for these things means pasting the same ~40 lines at the top of each of the relevant test files.

My current workaround is to manually map the module names in moduleNameMapper in package.json e.g.

"moduleNameMapper": {
    "braintree-web/client": "<rootDir>/__mocks__/braintree-web/client",
},

jackocnr avatar May 15 '18 15:05 jackocnr

If your mock is light to setup, and you use it a lot, you can add the jest.mock('@namespace/module/name', () => {…}) in your setup file.

We had the same issue for our translation lib, which is used in 200 of our test files.

flepretre avatar Jul 19 '18 09:07 flepretre

Thanks for the idea @flepretre but I just tried removing my moduleNameMapper entries in package.json, and my namespaced mocks still seem to be working! e.g. __mocks__/braintree-web/client.js for my code which imports "braintree-web/client".

¯\_(ツ)_/¯

jackocnr avatar Jul 23 '18 15:07 jackocnr

~~That's strange, I had the problem last week. I'll verify with the latest version off jest, but for me it didn't work.~~

I should have done some mistake somewhere with the mock because it's definitively working now! Nested modules mock are in fact fully supported 👍

flepretre avatar Jul 23 '18 15:07 flepretre

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs. Please note this issue tracker is not a help forum. We recommend using StackOverflow or our discord channel for questions.

github-actions[bot] avatar May 12 '21 14:05 github-actions[bot]