node.js - Jest: Find out if current module is mocked during runtime
问题描述
Is there a way i can find out during runtime if a module is mocked via jest?
Since mocked modules get required normally and therefore the code gets executed (as seen here: jest module executed even when mocked
We need this because we have checks on top of each file to fail early when a mandatory environment variable is not set, which causes our tests to fail even if the module is mocked.
if (!process.env.SOME_ENV) {
throw new Error(`Mandatory environment variable 'SOME_ENV' not set`)
}
We are looking for something like this:
if (!process.env.SOME_ENV && utils.isNotMocked(this)) {
throw new Error(`Mandatory environment variable 'SOME_ENV' not set`)
}
where utils.isNotMocked(this)
is the magic function which checks if the module is currently mocked.
解决方案
正如@jonrsharpe 提到的,通常不希望软件能够区分它是否在测试中。这意味着,您可能不会在任何模拟框架中找到您希望的功能。此外,提供这样一个特性可能存在更多基本问题,因为您可能有混合测试场景,其中某些测试用例使用模拟类的对象,而其他测试用例使用原始类的对象。
由于您在代码中使用早期退出机制作为一般模式,正如您所描述的那样:为此检查创建一个库函数怎么样 - 然后可以在测试期间再次加倍,以便在这种情况下函数不会抛出?
推荐阅读
- spring-boot - 在春季批处理部署程序分区处理程序中定期获取正在运行的工作节点的状态
- groovy - 找不到匿名类的匹配构造函数
- encoding - ISO Encoding 的 BOM(字节序标记)
- python - 使用 cvxopt 从给定的 Y(mean) 值获取有效边界的 X(std) 值?
- javascript - 我怎样才能在javascript中创建像'shold.be.a.integer'这样的方法?
- selenium - 如何启用对硒网格的视频支持?
- vb.net - 将图像动态加载到 datagridview 并且无法将图像正确加载到单个单元格中
- python - 基于两个txt文件之间最小距离的坐标配对
- javascript - 使用 useEffect 在 Scroll 上移动图像不起作用
- python - 如何通过分配变量从 sqlite3 获取特定数据