Skip to content

Instantly share code, notes, and snippets.

@nathan-hyan
Created November 29, 2022 14:50
Show Gist options
  • Save nathan-hyan/c3b6d02a39d26a4d6b2c69b47c365d9c to your computer and use it in GitHub Desktop.
Save nathan-hyan/c3b6d02a39d26a4d6b2c69b47c365d9c to your computer and use it in GitHub Desktop.
localStorage test configuration
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\"}')
})
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