Created
May 17, 2017 12:00
-
-
Save renaudtertrais/266de3dc2d001eae35734696f22c3ae9 to your computer and use it in GitHub Desktop.
A simple way to mock/unmock globals object methods or constant
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
/* global expect jest */ | |
const delay = ms => fn => setTimeout(fn, ms); | |
const mockGlobalProperty = globalObject => key => value => { | |
// save original implementation in order to unmock later | |
const original = globalObject[key]; | |
// mock key on the global object | |
Object.defineProperty(globalObject, key, { value, writable: true }); | |
// return an unmock function restoring original implementation | |
return () => mockGlobalProperty(globalObject)(key)(original); | |
}; | |
const mockWindow = mockGlobalProperty(global); | |
const mockSetTimeout = mockWindow('setTimeout'); | |
describe('delay()', () => { | |
it('should call seTimeout with the good params', () => { | |
const setTimeoutMock = jest.fn(); | |
const unmockSetTimeout = mockSetTimeout(setTimeoutMock); | |
const fn = jest.fn(); | |
delay(200)(fn); | |
expect(setTimeoutMock).toHaveBeenCalledWith(fn, 200); | |
// mandatory. try to comment this line and see how | |
// the 2nd test is affected by the mock | |
unmockSetTimeout(); | |
}) | |
it('should work with no mock', done => { | |
let thing = 'foo'; | |
delay(200)(() => thing = 'bar'); | |
expect(thing).toBe('foo'); | |
setTimeout(() => { | |
expect(thing).toBe('bar'); | |
done(); | |
}, 200); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
demo: https://repl.it/ICox/4