Reputation: 3932
I am publishing a (private) npm package and would like to publish mocks for it as well. I want these mocks to be picked up by jest's module mocking system.
The package is a react library that uses context and makes network requests. All of the library's functionality is self contained and fully tested. I would like the consumer to be able to treat this as a black box in tests, trusting that it works as expected. Thus, I would like to publish a mocked version of it for testing sake.
// The real component
const ComplicatedComponent = props => {
// Access context here
return <div> Something based on context <div/>
}
// The mocked component
const ComplicatedComponent = props => <>ComplicatedComponent</>
In a perfect world the consumer would simply be able to call
jest.mock('my-library');
As far as I can tell here: this is not possible out of the box. This seems to imply it is up to the consumer to write the mocks:
If the module you are mocking is a Node module (e.g.: lodash), the mock should be placed in the mocks directory adjacent to node_modules
Can anyone suggest a good approach to publishing mocks for my library to be used by jest?
Upvotes: 8
Views: 1160
Reputation: 1061
Reposting this comment from @Sean22 as the answer:
I did finally figure out how to do this. I included the modules that needed mocking in the regular __ mock __ subdirectory within my npm module. Then, within the code that imports the module, jest.mock('<npm_module>/path/to/mocked/code'), will use the mocked version of that npm module code
So, make sure your __mocks__/custom-mock.js
is included in the build for your package, and consuming apps will be able to use it 👍🏻
Upvotes: 2