首页 > 解决方案 > 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.

标签: node.jsunit-testingmockingjestjs

解决方案


正如@jonrsharpe 提到的,通常不希望软件能够区分它是否在测试中。这意味着,您可能不会在任何模拟框架中找到您希望的功能。此外,提供这样一个特性可能存在更多基本问题,因为您可能有混合测试场景,其中某些测试用例使用模拟类的对象,而其他测试用例使用原始类的对象。

由于您在代码中使用早期退出机制作为一般模式,正如您所描述的那样:为此检查创建一个库函数怎么样 - 然后可以在测试期间再次加倍,以便在这种情况下函数不会抛出?


推荐阅读