3

I have a private npm package that I use in multiple projects. Right now, each project has a copy of the mock for this internal library. Pretty much something like this in each jest setup file:

jest.mock('@myscope/shared-logger', () => ({
  createLogger: () => ({ /* ...mocked logger functions... */ }),
  // ... additional mocked exported functions
}));

My goal is to define the mock for this in the library itself and then share it. When looking at various mock libraries, one method I saw is to essentially define a mocked module, and export that. Then in a consuming project, import the mocked module and use it as a jest manual mock (e.g., this is what jest-mock-axios has you do).

Ideally I could simply define a mock in the library that jest discovers when running tests, but so far, I've not seen any way to accomplish this. Are manual mocks the best way to accomplish this or is there a different/recommended/better/more zero-setup-required way to do this?

Justin L.
  • 993
  • 14
  • 33
  • 1
    This looks like it could be a duplicate of https://stackoverflow.com/questions/58442280/publishing-mocks-for-an-npm-package-to-be-used-by-jests-module-mocking-system/71385437#71385437 ? The answer there is to [create a manual mock in your package](https://jestjs.io/docs/manual-mocks#mocking-user-modules), and make sure it’s in the published build. Consuming apps will be able to reference it with `jest.mock('/path/to/mocked/code')` – elstgav Mar 07 '22 at 18:08

0 Answers0