本文介绍了Jest中的resetAllMocks,resetModules,resetModuleRegistry,restoreAllMocks之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图用Jest围绕以下内容:

I'm trying to wrap my head around the following in Jest:

resetAllMocksresetModulesresetModuleRegistryrestoreAllMocks

我发现很难.

我阅读了开玩笑的文档,但不清楚.如果有人可以为我提供上述工作方式的示例,并且它们彼此不同,我将不胜感激.

I read the jest documentation but it's not too clear. I would appreciate it if someone can please provide me with an example of how the above work and they are different from each other.

推荐答案

以下部分说明了每个函数的行为及其相应的config指令.在config指令的情况下,解释的行为发生在每个测试之间,这使得它们与其他测试越来越孤立.

The following sections explain the behaviors of each function and its corresponding config directive. In the case of config directives, the explained behavior takes place in between each test making them more and more isolated from the other tests.

fn的引用意味着在每个操作下都有一个示例笑话模拟函数.

References to fn are implying a sample jest mock function under each of these actions.

重置所有模拟使用数据,而不是其实现.换句话说,它仅替换了笑话模拟函数的fn.mock.callsfn.mock.instances属性.

Resets all the mocks usage data, not their implementation. In other words, it only replaces fn.mock.calls and fn.mock.instances properties of a jest mock function.

clearAllMocks()的超集,该超集还负责将实现重置为no return函数.换句话说,它将用新的jest.fn()代替模拟函数,而不仅仅是其fn.mock.callsfn.mock.instances.

A superset of clearAllMocks() which also takes care of resetting the implementation to a no return function. In other words, it will replace the the mock function with a new jest.fn(), not just its fn.mock.calls and fn.mock.instances.

类似于resetAllMocks(),但有一个非常重要的区别.它恢复了间谍"的原始实现.因此,它就像用jest.fn()替换模拟,但用其原始实现替换间谍"..

Similar to resetAllMocks(), with one very important difference. It restores the original implementation of "spies". So, it goes like "replace mocks with jest.fn(), but replace spies with their original implementation".

因此,在我们使用jest.fn()(而非间谍)手动分配事物的情况下,我们必须自己进行实现恢复,因为jest不会这样做.

So, in cases where we manually assign things with jest.fn() (not spies), we have to take care of implementation restoration ourselves as jest won't be doing it.

它将重置Jest的模块注册表,该注册表是所有必需/导入模块的缓存.对此调用之后,Jest将重新导入任何必需的模块.想象一个干净的表象,而不必处理其他测试中所有被模拟的模块.

It resets Jest's module registry which is a cache for all required/imported modules. Jest will re-import any required module after a call to this. Imagine a clean slate without having to deal with all the mocked out modules in other tests.

它只是resetModules的别名,请参见:
https://github.com/facebook/jest/blob/7f69176c/packages/jest-runtime/src/index.ts#L1147

It's just an alias for resetModules, see:
https://github.com/facebook/jest/blob/7f69176c/packages/jest-runtime/src/index.ts#L1147

查看清除,重置和还原在操作上有何不同:
https://repl.it/@sepehr/jest-mock-api-重置-还原

See how clearing, resetting and restoring differ in action:
https://repl.it/@sepehr/jest-mock-api-reset-restore

这篇关于Jest中的resetAllMocks,resetModules,resetModuleRegistry,restoreAllMocks之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 21:14