Skip to content

Commit

Permalink
hook test
Browse files Browse the repository at this point in the history
  • Loading branch information
abhiShandy committed Jan 12, 2024
1 parent d4a9512 commit 411fc83
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions hooks/useLocalStorage.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { renderHook, act } from "@testing-library/react";
import { useLocalStorage } from "./useLocalStorage";

describe("useLocalStorage", () => {
beforeEach(() => {
localStorage.clear();
});

it("should initialize with fallback value if no stored value exists", () => {
const { result } = renderHook(() => useLocalStorage("testKey", "fallback"));

expect(result.current[0]).toBe("fallback");
});

it("should initialize with stored value if it exists", () => {
localStorage.setItem("testKey", JSON.stringify("storedValue"));

const { result } = renderHook(() => useLocalStorage("testKey", "fallback"));

expect(result.current[0]).toBe("storedValue");
});

it("should update stored value when setValue is called", () => {
const { result } = renderHook(() => useLocalStorage("testKey", "fallback"));

act(() => {
result.current[1]("newValue");
});

expect(result.current[0]).toBe("newValue");
expect(JSON.parse(localStorage.getItem("testKey"))).toBe("newValue");
});
});

0 comments on commit 411fc83

Please sign in to comment.