Mak
Mak

Reputation: 924

jest not picking up out of scope mock variables

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!

Upvotes: 2

Views: 2069

Answers (1)

Andreas Köberle
Andreas Köberle

Reputation: 110892

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()
}));

Upvotes: 2

Related Questions