javascript - Jest - 未导出的模拟函数

标签 javascript node.js unit-testing jestjs

我有一个文件,它导出一个依赖于私有(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 并确保它已被调用?

最佳答案

不可能模拟或监视未用作方法的现有函数。

__ab 应该驻留在不同的模块中,或者 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/

相关文章:

java - 使用 Freemarker 对 Spring Boot 应用程序进行单元测试抛出 NoSuchMessageException

javascript - HTML5 视频 : Add Subtitle text from a TextArea

javascript - 在不重新加载页面的情况下刷新 div 内容

javascript - 我可以在 .then 参数中使用 promise 吗?

node.js - 使用 Webpack 捆绑 sha3/二进制模块

c# - 单元测试抛出异常但看不到消息

javascript - 如何处理大文件、NodeJS 流和管道

ASP.Net AJAX JavaScript 序列化错误

javascript - 从 React(同构应用程序)进行 API 调用时出现“Access-Control-Allow-Origin”问题

Python 单元测试 : Nose @with_setup failing