Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the scope of mocks in jest?

In summary, I want to know:

  1. Are mocks contained to test files or affect multiple files?
  2. Is jest scoping the same as JavaScript scoping? A mock in the most inner scope has precedence over outer/global mocks with the same name.
  3. A followup question could be: which jest mock methods apply to the units and which apply to local and global scopes?

For example, in the following file system:

rootFolder/
  node_modules/
    externalModule/
      - index.js
  __mocks__/
    - externalModule.js
  src/
    - fileA.js
    - fileB.js
    - internalModule.js
    __mocks__/
      internalModule.js
    __tests__/
      - fileA.spec.js
      - fileB.spec.js

I have the following questions:

  1. Will jest.mock('../internalModule, () => customImplementation) in fileA.spec.js affect fileB.spec.js and vise versa?
  2. Similarly, will jest.mock('externalModule', () => customImplementation) in fileA.spec.js affect fileB.spec.js and vise versa?. Doing `jest.mock('Mocking external modules (node_modules)
  3. How do global mocks work? Will they be automatically loaded across files or do I have to explicitly do jest.mock('externalModule') for it to be initialized
  4. Will jest.mock('externalModule', () => customImplementation) take takes precedence over global mocks? Will it override the global mock across files?
  5. Will jest.spyOn(internalModule, 'someFunc').mockImplementationOnce(..) mock the implementation for the life of the unit or only a single call to someFunc() would reset the functionality?
  6. According to the docs jest.doMock, contrary to jest.mock, will NOT hoist the mock "up". But, up where? The file? And will it automatically unmock or reset it at the end of the unit? Or will it affect future units as well?
  7. Will jest.unmock('externalModule') for global mocks, reset it for every file?

I've seen very inconsistent behavior and no documentation explicitly explaining this. Furthermore, I've found documentation to be either all over the place or not concrete enough.

Thanks in advance.

P.S. I found other questions with similar titles, such as How to limit the scope of Jest mocked functions to a single test and Scoping in Jest when mocking functions but they don't answer my question.

like image 847
pgarciacamou Avatar asked Sep 12 '25 14:09

pgarciacamou


1 Answers

A spec file runs in isoloation to other specs unless included explicitly by the developer.

The exception here, is, it is possible to set up globals to run.

Treat each test within a spec as it's own application effectively.

They should not interact with each other. But if you import a file, that imports another file (and so on) all those files will be involved in the test and can affect the outcome (depending on what those file do/behave, but thats why we have tests - to find out).

like image 99
DrogoNevets Avatar answered Sep 15 '25 03:09

DrogoNevets