Jestjs 没有回调作为参数的模拟函数

Jestjs 没有回调作为参数的模拟函数,jestjs,babel-jest,ts-jest,jest-fetch-mock,Jestjs,Babel Jest,Ts Jest,Jest Fetch Mock,我有dh.js const checkDExistsCallback = (err, dResp) => { if (err) cbResp.error('failed'); if (dResp.length > 0) checkDCollectionExists(); else cbResp.error('Not found.'); }; const checkDCollectionExists = ()

我有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 }
在我的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(); 
});

在dh.js中,调用checkDExistsCallback函数时,checkDCollectionExists在满足“if”条件后存在。当您查看dh.test.ts文件时,我在开始时模拟了checkDCollectionExists函数,但在运行测试时,它没有调用模拟的函数,而是调用了实际的函数。你能帮我弄清楚吗?

一个在定义它的同一个模块中使用的函数不能被模拟,除非它一直被用作可以模拟的对象上的方法,例如

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

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

checkDCollectionExists
需要移动到另一个模块,或者需要将两个功能作为一个单元进行测试。需要模拟的是数据库调用。

谢谢,所以我需要在声明此module.exports.checkDCollectionExists()后从“module.exports={checkDExistsCallback,checkDCollectionExists}”中删除函数;您需要有
module.exports={CheckDexistScalBack
以使其作为
模块提供。导出。checkDCollectionExists
并可作为
dhExport.checkDCollectionExists
进行模拟。请注意,这是一种变通方法,不是一种公认的方法。它不适合ES模块。您有任何建议以正确的方式进行更改吗?我想到了ch使用另一个参数(如下一个回调(checkDCollectionExists))更改函数(checkDExistsCallback)因此,在所有地方都可以很容易地进行模拟。在您看来,这种方式好吗?如果这个函数的可测试性是一个问题,那么将其移动到另一个模块,这样通常可以使用jest.mock进行模拟。可测试性是决定代码应如何在模块之间分割的因素之一。在这种特定情况下,我看不出原因这是因为checkDCollectionExists很简单,不会增加测试的复杂性。相反,模拟genericQueryCall,它位于另一个模块中,因此可以模拟,不是吗?