我试图了解什么时候可以只导入模拟,什么时候需要导入模拟并仍然使用 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 calljest.mock('module_name')
.
Warning: If we want to mock Node's core modules (e.g.:
fs
orpath
), 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/