Skip to content

Instantly share code, notes, and snippets.

@jogilvyt
Last active January 19, 2021 17:04
Show Gist options
  • Save jogilvyt/de1229a4b60c40be6f5d8b5882237e7f to your computer and use it in GitHub Desktop.
Save jogilvyt/de1229a4b60c40be6f5d8b5882237e7f to your computer and use it in GitHub Desktop.
Tests for useStateWithLocalStorage
import { renderHook, act } from "@testing-library/react-hooks";
import useStateWithLocalStorage from "./useStateWithLocalStorage";
const TEST_KEY = "key";
const TEST_VALUE = { test: "test" };
describe("useStateWithLocalStorage", () => {
it("should set localStorage with default value", () => {
renderHook(() => useStateWithLocalStorage(TEST_VALUE, TEST_KEY));
expect(JSON.parse(localStorage.getItem(TEST_KEY))).toEqual(TEST_VALUE);
});
it("should set the default value from localStorage if it exists", () => {
// set the localStorage to the test value
localStorage.setItem(TEST_KEY, JSON.stringify(TEST_VALUE));
// initialise with an empty object
const { result } = renderHook(() => useStateWithLocalStorage({}, TEST_KEY));
// check that the value is what is stored in localStorage (and not an empty object)
const [value] = result.current;
expect(value).toEqual(TEST_VALUE);
// expect value to be taken from localStorage (rather than empty object)
expect(JSON.parse(localStorage.getItem(TEST_KEY))).toEqual(TEST_VALUE);
});
it("should update localStorage when state changes", () => {
// initialise with test object
const { result } = renderHook(() =>
useStateWithLocalStorage(TEST_VALUE, TEST_KEY)
);
const [, setValue] = result.current;
// set the state to something new
const newValue = { anotherValue: "Some value" };
act(() => {
setValue(newValue);
});
// localStorage should have updated to new value
expect(JSON.parse(localStorage.getItem(TEST_KEY))).toEqual(newValue);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment