Jest Mock Any Property on Window Utility - with automatic cleanup.
Last active
October 25, 2024 13:57
-
-
Save mayank23/7b994385eb030f1efb7075c4f1f6ac4c to your computer and use it in GitHub Desktop.
Jest Mock Any Property on Window Utility - with automatic cleanup
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
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; | |
}); | |
}; | |
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
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
not working for me with node 8