Skip to content

Instantly share code, notes, and snippets.

@hongkheng
Last active December 7, 2018 05:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hongkheng/f12a2229bd6d68ed274a6e977ed52c7b to your computer and use it in GitHub Desktop.
Save hongkheng/f12a2229bd6d68ed274a6e977ed52c7b to your computer and use it in GitHub Desktop.
Jest mocks
// 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