forked from MergeFi/frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseCrossTabStorage.test.ts
More file actions
64 lines (47 loc) · 2.01 KB
/
Copy pathuseCrossTabStorage.test.ts
File metadata and controls
64 lines (47 loc) · 2.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import { renderHook } from "@testing-library/react";
import { useCrossTabStorage } from "./useCrossTabStorage";
function dispatchStorageEvent(key: string | null, newValue: string | null) {
window.dispatchEvent(
new StorageEvent("storage", { key, newValue, storageArea: window.localStorage }),
);
}
describe("useCrossTabStorage", () => {
it("invokes onChange with the new value when the watched key changes", () => {
const onChange = jest.fn();
renderHook(() => useCrossTabStorage("watched_key", onChange));
dispatchStorageEvent("watched_key", "new-value");
expect(onChange).toHaveBeenCalledTimes(1);
expect(onChange).toHaveBeenCalledWith("new-value");
});
it("invokes onChange with null when the watched key is removed", () => {
const onChange = jest.fn();
renderHook(() => useCrossTabStorage("watched_key", onChange));
dispatchStorageEvent("watched_key", null);
expect(onChange).toHaveBeenCalledWith(null);
});
it("ignores storage events for unrelated keys", () => {
const onChange = jest.fn();
renderHook(() => useCrossTabStorage("watched_key", onChange));
dispatchStorageEvent("some_other_key", "whatever");
expect(onChange).not.toHaveBeenCalled();
});
it("removes its listener on unmount", () => {
const onChange = jest.fn();
const { unmount } = renderHook(() => useCrossTabStorage("watched_key", onChange));
unmount();
dispatchStorageEvent("watched_key", "after-unmount");
expect(onChange).not.toHaveBeenCalled();
});
it("re-subscribes under the new key when the key argument changes", () => {
const onChange = jest.fn();
const { rerender } = renderHook(
({ key }: { key: string }) => useCrossTabStorage(key, onChange),
{ initialProps: { key: "key_a" } },
);
rerender({ key: "key_b" });
dispatchStorageEvent("key_a", "should-be-ignored-now");
expect(onChange).not.toHaveBeenCalled();
dispatchStorageEvent("key_b", "should-fire");
expect(onChange).toHaveBeenCalledWith("should-fire");
});
});