Skip to content

Instantly share code, notes, and snippets.

@renaudtertrais
Created May 17, 2017 12:00
Show Gist options
  • Save renaudtertrais/266de3dc2d001eae35734696f22c3ae9 to your computer and use it in GitHub Desktop.
Save renaudtertrais/266de3dc2d001eae35734696f22c3ae9 to your computer and use it in GitHub Desktop.
A simple way to mock/unmock globals object methods or constant
/* 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);
});
});
@renaudtertrais
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment