2

I have a logging class that is used across my entire app and I am trying to mock it using jest mock.

Here's my code:

const mockLogger = {
  'error': jest.fn()
};
jest.mock('../../config/log', () => mockLogger);

I need to be able to check if log.error has been called so I need to declare the mock implementation of log out of scope. However I keep getting the following error:

 ReferenceError: mockLogger is not defined

      20 |   'error': jest.fn()
      21 | };
    > 22 | jest.mock('../../config/log', () => mockLogger);

The funny thing is that I have a very similar piece of code that works in another project. I cant figure out why I am getting this error.

I know this is an issue with scoping but not sure what to do about it. Any input on this will really be helpful!

Andreas Köberle
  • 106,652
  • 57
  • 273
  • 297
Mak
  • 894
  • 2
  • 8
  • 24
  • Possible duplicate of [Service mocked with Jest causes "The module factory of jest.mock() is not allowed to reference any out-of-scope variables" error](https://stackoverflow.com/questions/44649699/service-mocked-with-jest-causes-the-module-factory-of-jest-mock-is-not-allowe) – Swaraj Giri Feb 25 '19 at 04:03

1 Answers1

2

The problem is that the jest.mock calls are hoisted to the outer scope of the test file during runtime. So you have no way to use any variable from inside of the test. The easiest in your case would be :

jest.mock('../../config/log', () => ({
  'error': jest.fn()
}));
Andreas Köberle
  • 106,652
  • 57
  • 273
  • 297
  • Please have a look at this i am facing same problem : https://stackoverflow.com/questions/73977384/the-module-factory-of-jest-mock-is-not-allowed-to-reference-any-out-of-scope – user2028 Oct 07 '22 at 08:44