Chandrasekar Kesavan
Chandrasekar Kesavan

Reputation: 795

Mock function without callback as parameter

I have dh.js

const checkDExistsCallback = (err, dResp) => {
  if (err)    
    cbResp.error('failed');    

  if (dResp.length > 0) 
    checkDCollectionExists();  
  else 
    cbResp.error('Not found.');  
};
    
const checkDCollectionExists = () => 
{  
  let query = `select sid from tablename where sid = '${objRequestData.dName}' limit 1;`;
  genericQueryCall(query, checkDCollCallback);
}

module.exports = {checkDExistsCallback , checkDCollectionExists }

In my dh.test.ts

const dhExport = require("./DensityHookReceive");
dhExport.checkDCollectionExists = jest.fn().mockImplementation(() => {});

test('check req dh is exists', () => {
  dhExport.checkDExistsCallback(false, '[{}]');
  expect(dhExport.checkDCollectionExists).toBeCalled(); 
});

In dh.js checkDExistsCallback function is invoked the checkDCollectionExists after satisfied the 'if' condition. When you look into the dh.test.ts file I mocked the checkDCollectionExists function in the beginning, but while running the test it did not invoke the mocked function it invokes the actual function. Can you help me to figure it out?

Upvotes: 1

Views: 564

Answers (1)

Estus Flask
Estus Flask

Reputation: 222464

A function that is used in the same module it was defined cannot be mocked, unless it's consistently used as a method on an object that could be mocked, e.g.

  if (dResp.length > 0) 
    module.exports.checkDCollectionExists();  

instead of

  if (dResp.length > 0) 
    checkDCollectionExists();  

checkDCollectionExists needs to be either moved to another module, or two functions need to be tested as a single unit. It's database call that needs to be mocked.

Upvotes: 1

Related Questions