Skip to content

Instantly share code, notes, and snippets.

@mayank23
Last active June 20, 2023 20:00
Show Gist options
  • Save mayank23/7b994385eb030f1efb7075c4f1f6ac4c to your computer and use it in GitHub Desktop.
Save mayank23/7b994385eb030f1efb7075c4f1f6ac4c to your computer and use it in GitHub Desktop.
Jest Mock Any Property on Window Utility - with automatic cleanup

Jest Mock Any Property on Window Utility - with automatic cleanup.

export default const mockWindowProperty = (property, value) => {
const { [property]: originalProperty } = window;
delete window[property];
beforeAll(() => {
Object.defineProperty(window, property, {
configurable: true,
writable: true,
value,
});
});
afterAll(() => {
window[property] = originalProperty;
});
};
import mockWindowProperty from './mock-window-property'
describe('my test', () => {
mockWindowProperty('localStorage', {
setItem: jest.fn(),
getItem: jest.fn(),
removeItem: jest.fn(),
});
it('works as expected', () => {
window.localStorage.setItem('abc');
expect(window.localStorage.setItem).toHaveBeenCalledWith('abc');
});
});
@n-dragon
Copy link

n-dragon commented Jan 6, 2020

not working for me with node 8

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