jest.createMockFromModule vs jest.mock

Viewed 306

I'm learning unit testing with jest. I can not understand the difference between the jest.createMockFromModule and jest.mock. Seems that they do the same? Can someone please explain me the difference?

1 Answers

jest.mock - does module auto-mocking and implicitly replaces imported module in the test file. If you provide fabric function by the second argument it will define the module implementation like:

jest.mock('./moduleName', () => ({
    default: 12345 // default constant definition
    MyClass: { // Named export object or class definition
        get: () => { /* get method class definition */ }
    }
    /* etc... */
}))

You also can override only part of imported module.

jest.createMockFromModule - generates auto-mocked module and returns it as a value. It useful in the manual mocking. You can override required module values:

// __mocks__/MyModule.js

const moduleName = jest.createMockFromModule('./moduleName');
moduleName.someNamedImport = () => 12345; // override method implementation

expect(moduleName.default.mocked).toBeTruthy(); // to check default import auto-mocking
expect(moduleName.someNamedImport()).toBe(12345)
Related