Why my module does not get mocked as expected in Jest?

Posted on

There are some cases where you want to mock some module and you have everything setup correctly in code. Despite that hard work or writing Unit tests, your test is failing as the module is still returning the original version and not the mocked version.

One of the reasons for this issue can be the order of statements. E.g, if you have mocked a module at line #5, but there are some other require statements at line #1,2,3,4, then it may be the case that the same module is used in those required modules (at line #1,2,3,4). Carefully, look for that module in those modules and then what you have to do is to change the order of lines. take #5 statement before the required module. It should ideally solve your issue.

const Alerter = require('../../../src/classes/abc.class'); 
const alerter = require('../../../src/helpers/def'); 

jest.mock('../../../src/helpers/jkl', () => 
  jest.fn().mockReturnValue({ test: 'test' }
)); 
const myLogger = {   
   debug: jest.fn(),   error: jest.fn(), 
}; 

jest.doMock('../../../src/logger', () => ({
   getLogger: () => myLogger, 
})); 

Should be

const myLogger = {
  debug: jest.fn(),
  error: jest.fn(),
};
jest.doMock('../../../src/logger', () => ({
  getLogger: () => myLogger,
}));

const Alerter = require('../../../src/classes/abc.class');
const alerter = require('../../../src/helpers/def');

jest.mock('../../../src/helpers/jkl', () => jest.fn().mockReturnValue({ test: 'test' }));

Leave a Reply

Your email address will not be published. Required fields are marked *