使用 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屋!