模拟函数,不带回调作为参数 [英] Mock function without callback as parameter
问题描述
我有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中
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();
});
在dh.js中,满足"if"条件后,调用 checkDCollectionExists 的 checkDExistsCallback 函数.当您查看dh.test.ts文件时,我在一开始就对checkDCollectionExists函数进行了模拟,但是在运行测试时,它没有调用模拟的功能,而是调用了实际的功能.你能帮我弄清楚吗?
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?
推荐答案
在已定义的同一模块中使用的函数不能被模拟,除非将其始终用作可以被模拟的对象的方法,例如
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();
代替
if (dResp.length > 0)
checkDCollectionExists();
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.
这篇关于模拟函数,不带回调作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!