简体   繁体   English

模拟与导入然后模拟

[英]Mock vs Import Then Mock

I'm trying to understand when I can just import a mock vs when I need to import the mock and still use jest.mock in the test file.我试图了解什么时候可以只导入一个模拟,什么时候我需要导入模拟并且仍然在测试文件中使用jest.mock I'm looking at the manual-mocks example from Jest's Github.我正在查看 Jest 的 Github 中的手动模拟示例

One Step Module Mocking一步模块 Mocking

In the Lodash test, Lodash is mocked in the __mocks__ directory using createMockFromModule , exported, and simply imported using the standard module import and used directly in the test (no additional mocking).在 Lodash 测试中, Lodash__mocks__目录中使用createMockFromModule进行模拟,导出,并使用标准模块导入简单地导入并直接在测试中使用(无需额外的模拟)。

Two Step Mocking两步 Mocking

In that same project, the User model is exported and there is a separate User mock file .在同一个项目中, 用户 model 被导出,并且有一个单独的用户模拟文件 But in the User mocked test , the User is imported but there is an additional step using jest.mock('../models/user');但是在User mocked test中, User 被导入但是还有一个额外的步骤使用jest.mock('../models/user');

My Question/Confusion我的问题/困惑

Why would the Lodash test not require the additional jest.mock in the test file, or why does the User test require it?为什么 Lodash 测试不需要测试文件中的额外jest.mock ,或者为什么 User 测试需要它? In the project, it seems like I can test both actual and mocked User implementation, but Lodash will only use the mocked implementation, even though both are created/exported using createMockFromModule in the __mocks__ directories.在项目中,我似乎可以测试实际和模拟用户实现,但Lodash将只使用__mocks__目录中的createMockFromModule创建/导出的。

The difference is that lodash is Node module and user is local module, the latter needs jest.mock('../models/user') in order for a mock from __mocks__ to be used.不同之处在于lodash是 Node 模块,而user是本地模块,后者需要jest.mock('../models/user')才能使用来自__mocks__的模拟。

As the documentation states,正如文件所述,

If the module you are mocking is a Node module (eg: lodash ), the mock should be placed in the __mocks__ directory adjacent to node_modules (unless you configured roots to point to a folder other than the project root) and will be automatically mocked.如果您的模块 mocking 是 Node 模块(例如: lodash ),则 mock 应放置在与 node_modules 相邻的__mocks__目录中(除非您将 root 配置为指向项目 root 以外的文件夹)并且将自动模拟。 There's no need to explicitly call jest.mock('module_name') .无需显式调用jest.mock('module_name')

Warning: If we want to mock Node's core modules (eg: fs or path ), then explicitly calling eg jest.mock('path') is required, because core Node modules are not mocked by default.警告:如果我们想模拟 Node 的核心模块(例如: fspath ),则需要显式调用例如jest.mock('path') ,因为默认情况下不会模拟核心 Node 模块。

This allows to avoid accidental collisions between mocks for NPM packages and local modules of the same name.这可以避免 NPM 包的模拟与同名的本地模块之间的意外冲突。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM