0

I am new at unit tests and I need to write a test for localstorage using jest, but not sure how I should approach the test and what I would need to test. Thankful for any help or tips since as I said I am completely new to this. The code looks like this:

function useLocalStorage(key, initialValue) {

const [storedValue, setStoredValue] = useState(() => {
if (typeof window === 'undefined') {
  return initialValue;
}
try {
  const item = window.localStorage.getItem(key);
  return item ? JSON.parse(item) : initialValue;
} catch (error) {
  console.log(error);
  return initialValue;
}
});

const setValue = value => {
try {
  const valueToStore =
    value instanceof Function ? value(storedValue) : value;
  setStoredValue(valueToStore);
  if (typeof window !== 'undefined') {
    window.localStorage.setItem(key, JSON.stringify(valueToStore));
  }
} catch (error) {
  console.log(error);
}
};
return [storedValue, setValue];
}
  • Check out Jest's spyOn function. You can use it to mock existing APIs, like the localStorage API. Then you can assert that the set and get functions were called in your test in the way you expect. https://jestjs.io/docs/jest-object#jestspyonobject-methodname – Regan Karlewicz Jul 10 '22 at 17:22
  • But what exactly do I need to test? Is it just that get and set item is correct or is it anything else also? –  Jul 10 '22 at 18:17
  • 1
    That is up to you and what you think you should test; your tests should test the behavior of the function, not that `localStorage` works - that's up to the team that implements `localStorage`. You can spy on the arguments used when you use `localStorage` functions and how your function behaves when something goes wrong for example – doublethink13 Jul 11 '22 at 18:22
  • 1
    Exactly what @doublethink suggested. Your job isn't to test localStorage, but rather is to test the function calling localStorage. So what you are testing is that `useLocalStorage` functions how you expect. So you can call `useLocalStorage` in your test, use the returned functions, and assert that those returned functions calls localStorage APIs in the way you expect. – Regan Karlewicz Jul 11 '22 at 19:27

0 Answers0