Skip to content

Instantly share code, notes, and snippets.

@RrNn
Forked from mayank23/README.md
Created August 9, 2019 19:43
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 RrNn/0249376ec95d218e4532add95a0b874a to your computer and use it in GitHub Desktop.
Save RrNn/0249376ec95d218e4532add95a0b874a 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