用Jest重置单个模块 [英] Reset single module with Jest
问题描述
jest.resetModules()
清除所有模块的require缓存,但是有没有办法只清除单个模块呢?无法使用 require.cache
,因为Jest似乎绕过了它.
jest.resetModules()
clears the require cache for all modules but is there a way to clear it for just a single module? Can't use require.cache
as Jest appears to bypass it.
我正在测试有状态的Node模块(即,它依赖于对 require
的多次调用返回相同实例的事实).对于我的测试,我需要重置模块的状态以测试不同的场景. jest.resetModules()
可以工作,但是随后我需要重新 require
一些其他不需要重置的模拟模块.
I'm testing a Node module which is stateful (i.e. it relies on the fact that multiple calls to require
return the same instance). For my test I need to reset the state of the module to test different scenarios. jest.resetModules()
works but then I need to re-require
some other mocked modules which didn't need to be reset.
推荐答案
自Jest 24开始,您现在可以使用 jest.isolateModules
来做到这一点.
Since Jest 24 you can now use the jest.isolateModules
to do this.
假设您只想重置某个模块,那么您应该在 jest.isolateModules
的回调中要求该模块:
Let's say you only want to reset a certain module, then you should require that in the callback of jest.isolateModules
:
let myModule;
jest.isolateModules(() => {
myModule = require('my-certain-module');
});
这篇关于用Jest重置单个模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!