Skip to content

Instantly share code, notes, and snippets.

@igorvieira
Forked from mayank23/README.md
Created January 14, 2021 17:43
Show Gist options
  • Save igorvieira/c0774006f67e1c35a12ad2ae1f9535cf to your computer and use it in GitHub Desktop.
Save igorvieira/c0774006f67e1c35a12ad2ae1f9535cf 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');
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment