Last active
December 7, 2018 05:45
-
-
Save hongkheng/f12a2229bd6d68ed274a6e977ed52c7b to your computer and use it in GitHub Desktop.
Jest mocks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Show how to setup and create a simple Jest manual mocks | |
// Beginning of the example... custom.test.js | |
// Assume your Custom ES module and import it | |
import Custom from './Custom'; | |
// Has to be after it is imported, use the file path where the module is located | |
jest.mock('./Custom', () => { | |
const mockMethod1= jest.fn() | |
const mockMethod2 = jest.fn() | |
return jest.fn().mockImplementation(() => { | |
return { | |
method1: mockMethod1, | |
method2: mockMethod2 | |
} | |
}) | |
}) | |
beforeEach(() => { | |
// do .mockClear() to reset mocks | |
}) | |
test('some test case', () => { | |
// Initialize the obj | |
const cus = new Custom() | |
// override the mock method's the return value | |
cus.method1.mockReturnValue('hi') | |
// override the implementation | |
cus.method2.mockImplementation( () => { | |
return 'override' | |
}) | |
}) | |
// Mocking export function | |
// Original implementation: singleEntity.js | |
export default singleEntity(ref, fan) { | |
if (ref === 'some') { | |
fan.someOne() | |
} | |
} | |
// Mocked | |
const singleEntityRenamed = require('singleEntity') | |
singleEntityRenamed.singleEntity = jest.fn() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment