javascript - 模拟与导入然后模拟

标签 javascript mocking jestjs

我试图了解什么时候可以只导入模拟,什么时候需要导入模拟并仍然使用 jest.mock在测试文件中。我在看 manual-mocks example来自 Jest 的 Github。
一步模块模拟
在 Lodash 测试中,Lodash is mocked__mocks__使用 createMockFromModule 的目录,导出,并简单地 imported using the standard module import and used directly in the test (没有额外的 mock )。
两步模拟
在同一个项目中,User model is exported并且有一个 separate User mock file .但是在 User mocked test ,用户已导入,但有一个使用 jest.mock('../models/user'); 的附加步骤
我的问题/困惑
为什么 Lodash 测试不需要额外的 jest.mock在测试文件中,或者为什么用户测试需要它?在项目中,我似乎可以测试实际和模拟用户实现,但 Lodash 将只使用模拟实现,即使两者都是使用 createMockFromModule 创建/导出的。在 __mocks__目录。

最佳答案

区别在于 lodash是节点模块和user是本地模块,后者需要jest.mock('../models/user')为了来自 __mocks__ 的模拟要使用的。
the documentation状态,

If the module you are mocking is a Node module (e.g.: 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. There's no need to explicitly call jest.mock('module_name').


Warning: If we want to mock Node's core modules (e.g.: fs or path), then explicitly calling e.g. jest.mock('path') is required, because core Node modules are not mocked by default.


这可以避免 NPM 包的模拟与同名的本地模块之间的意外冲突。

关于javascript - 模拟与导入然后模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63327443/

相关文章:

javascript - 正则表达式:将文本拆分为单词并保留换行符

javascript - 如何为 Google Maps API directionService 使用现有标记而不是定义新标记?

c# - 如何在具有多个间接级别的项目中使用单元测试

c# - 如何在没有公共(public)构造函数的情况下模拟/伪造/ stub 密封的 OracleException?

c++ - 在 gTest 中模拟 FreeRTOS 函数

javascript - Window.top 在 WorkerGlobalScope 中未定义

javascript - 使用预签名 URL 上传后,AWS S3 上的文件包含额外信息

javascript - TypeError [ERR_INVALID_ARG_TYPE] : The "data" argument must be of type string or an instance of Buffer, TypedArray,或DataView

unit-testing - jest 是否会自动恢复测试模块之间的模拟模块?

javascript - 使用 Jest 和 Webpack 别名进行测试