我有一个文件,它导出一个依赖于私有(private)函数的函数:
function __a(filePath, someFunction){
// do some file request
someFunction(filePath)
}
function b(filePath){
__a(filePath, require)
}
module.exports = {
b: b
}
我想测试私有(private)函数 __a
toHaveBeenCalledWith
一些参数,以便 __a
实际上不会尝试获取我的一些文件不能保证存在。
我理解这样的概念:当我导入 b
时,我将获得对该函数的引用,而 __a
就存在于它的范围内,我可以'无法访问它,因此使用以下内容:
import appResources from './index';
// ... test
jest.spyOn(applicationResources, '__a').mockImplementationOnce(myParams);
如何避免此处执行 __a
并确保它已被调用?
最佳答案
不可能模拟或监视未用作方法的现有函数。
__a
和 b
应该驻留在不同的模块中,或者 a
应该用作同一模块中的方法。对于 CommonJS 模块,可以使用现有的 exports
对象:
exports.__a = function __a(filePath, someFunction){
// do some file request
someFunction(filePath)
}
exports.b = function b(filePath){
exports.__a(filePath, require)
}
请注意,module.exports
未被替换,否则无法将其引用为exports
。
关于javascript - Jest - 未导出的模拟函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54484088/