Jest Mock Any Property on Window Utility - with automatic cleanup.
-
-
Save igorvieira/c0774006f67e1c35a12ad2ae1f9535cf 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