I am having problem writing test for useSessionStorage hook. I am trying to write first test to check if my hooks sets value in SessionStorage to initial when used. The hook works in app as it suppose to but when it comes to test it fails and test returns value NULL instead of the one given as argument. Is my approach incorrect when it comes to testing it? How can I do it?
hook
import { useState } from "react";
const useSessionStorage = (key, initialValue) => {
const [storedValue, setStoredValue] = useState(() => {
try {
const checkSessionStorage = sessionStorage.getItem(key);
if (checkSessionStorage) {
return JSON.parse(checkSessionStorage);
} else {
return initialValue;
}
} catch (err) {
console.log(err);
}
});
const setValue = (value) => {
try {
const valueToStore =
value instanceof Function ? value(storedValue) : value;
setStoredValue(valueToStore);
sessionStorage.setItem(key, JSON.stringify(valueToStore));
} catch (error) {
console.log(error);
}
};
return [storedValue, setValue];
};
export default useSessionStorage;
test
import { renderHook, act } from "@testing-library/react-hooks";
import useSessionStorage from "./useSessionStorage";
const testKey = "key";
const testValue = "test";
describe("useSessionStorage", () => {
test("it should set sessionStorage with initial value", () => {
renderHook(() => useSessionStorage(testKey, testValue));
expect(JSON.parse(sessionStorage.getItem(testKey))).toEqual(testValue);
});
});