Created
November 29, 2022 14:50
-
-
Save nathan-hyan/c3b6d02a39d26a4d6b2c69b47c365d9c to your computer and use it in GitHub Desktop.
localStorage test configuration
This file contains hidden or 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
describe('testing localStorage', () => { | |
// This following snippet is from https://amitd.co/code/testing/spying-on-localstorage-in-jest | |
// Thank you so much Amit Dhamu for this implementation | |
jest.spyOn(Object.getPrototypeOf(window.localStorage), 'setItem'); | |
Object.setPrototypeOf(window.localStorage.setItem, jest.fn()); | |
it('saves to localStorage when clicked on button', () => { | |
render(<Component />); | |
const button = screen.getByRole('button'); | |
fireEvent.click(button); | |
expect(window.localStorage.setItem).toHaveBeenCalledWith('key', '{\"hello\": \"world\"}') | |
}) |
This file contains hidden or 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
interface Data { | |
hello: string; | |
} | |
function Component() { | |
const handleSaveToLocalStorage = (data: Data) => { | |
localStorage.setItem('key', JSON.stringify(data)) | |
} | |
return ( | |
<div> | |
<button onClick={() => handleSaveToLocalStorage({hello: 'world'})}> | |
Save Data to localStorage | |
</button> | |
</div> | |
) | |
} | |
export default Component |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment