简体   繁体   中英

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. I'm looking at the manual-mocks example from Jest's Github.

One Step Module 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).

Two Step Mocking

In that same project, the User model is exported and there is a separate User mock file . But in the User mocked test , the User is imported but there is an additional step using 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? 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.

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.

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. There's no need to explicitly call 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.

This allows to avoid accidental collisions between mocks for NPM packages and local modules of the same name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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