Jest: Manual mock discovery for Node packages is unclear (to me)

Created on 20 Sep 2015  ยท  5Comments  ยท  Source: facebook/jest

The documentation says the mock should be placed in the same parent directory as the 'node_modules' folder, e.g.

var lodash = require('lodash'); // /__mocks__/lodash.js :)
.
โ”œโ”€โ”€ __mocks__
โ”‚ย ย  โ””โ”€โ”€ lodash.js
โ””โ”€โ”€ node_modules
    โ””โ”€โ”€ lodash
        โ””โ”€โ”€ index.js

This works fine however I wondered how you would mock a non-main module within a package, e.g.

var lodash = require('lodash/array/compact'); // Where should the manual mock live?

I gave this a shot but I'm guessing it's not correct:

.
โ”œโ”€โ”€ __mocks__
โ”‚ย ย  โ””โ”€โ”€ lodash
โ”‚ย ย      โ””โ”€โ”€ array
โ”‚ย ย          โ””โ”€โ”€ compact.js // ?
โ””โ”€โ”€ node_modules
    โ””โ”€โ”€ lodash
        โ””โ”€โ”€ index.js

In addition I've noticed that package mocks seem to be picked up in any '__mocks__' dir, even those which aren't adjacent to the 'node_modules' dir, e.g.

var lodash = require('lodash'); // /src/__mocks__/lodash.js :)
.
โ”œโ”€โ”€ node_modules
โ”‚ย ย  โ””โ”€โ”€ lodash
โ”‚ย ย      โ””โ”€โ”€ index.js
โ””โ”€โ”€ src
    โ””โ”€โ”€ __mocks__
        โ””โ”€โ”€ lodash.js

Any insight would be much appreciated.

Most helpful comment

I recommend using jest.mock('path/to/module', () => {โ€ฆ}) instead.

All 5 comments

Any update? I have same problem.

Does anybody have some workaround of this issue?

There is no workaround for this yet. Blocked on #599. I'll likely add a way for jest to properly mock node_modules (and internals) and also will make it more strict to colocate mocks.

Manually call setMock will help.

I want to mock some/other/library in node_modules, then I create the path under __mocks__ folder, like:

__mocks__/
--some/
----other/
------library.js

Then call jest.setMock('some/other/library', require.requireActual('../__mocks__/some/other/library') in the test. After that when calling require('some/other/library'), jest will use the mock instead.

Please check https://github.com/zyeeda/cde.io/tree/bleeding-edge/src/config for example.

I recommend using jest.mock('path/to/module', () => {โ€ฆ}) instead.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

GrigoryPtashko picture GrigoryPtashko  ยท  3Comments

paularmstrong picture paularmstrong  ยท  3Comments

jardakotesovec picture jardakotesovec  ยท  3Comments

StephanBijzitter picture StephanBijzitter  ยท  3Comments

hramos picture hramos  ยท  3Comments