Skip to content

Instantly share code, notes, and snippets.

@davidnguyen11
Last active June 17, 2024 14:47
Show Gist options
  • Save davidnguyen11/ee017fb1cf6659a920b40ec721498058 to your computer and use it in GitHub Desktop.
Save davidnguyen11/ee017fb1cf6659a920b40ec721498058 to your computer and use it in GitHub Desktop.
import { stub } from 'sinon';
describe('Testing localStorage', () => {
let getFunc;
let setFunc;
// Clone the original "localStorage"
const originalLocalStorage = window.localStorage;
beforeEach(() => {
getFunc = stub();
setFunc = stub();
Object.defineProperty(window, 'localStorage', {
value: {
getItem: getFunc,
setItem: setFunc,
},
writable: true
});
});
afterEach(() => {
// Revert the fake localStorage in "beforeEach" block
Object.defineProperty(window, 'localStorage', {
value: { ...originalLocalStorage },
writable: true
});
});
it('should call localStorage.getItem', () => {
getFunc.returns('{"foo": "bar"}');
// Add your test related to function using "localStorage" here
// Should assert or expect here to test the "getItem" is called or not
// Jest
expect(getFunc.called).toBeTruthy();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment