Skip to content

Commit

Permalink
test: test useAccessor hook
Browse files Browse the repository at this point in the history
  • Loading branch information
iamogbz committed Sep 21, 2020
1 parent 23d644e commit 6b4dfbb
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 5 deletions.
14 changes: 9 additions & 5 deletions src/hooks/useAccessor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,13 @@ export function useAccessor<R>(
ref.current = value;
}, []);

if (value) setValue(value);
return [
getValue,
React.useMemo(() => (value ? undefined : setValue), [setValue, value]),
];
// If a value was initially provided then no setter is returned
const maybeSetValue = React.useMemo(function getSetValue() {
return value === undefined ? setValue : undefined;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// If a value was initially provided then keep the ref updated
if (!maybeSetValue) setValue(value);

return [getValue, maybeSetValue];
}
28 changes: 28 additions & 0 deletions tests/hooks.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,36 @@
import { act, renderHook } from "@testing-library/react-hooks";
import { useDispatch } from "src";
import { createContextWithValue } from "src/createContext";
import { useAccessor } from "src/hooks/useAccessor";
import { useObservable } from "src/hooks/useObservable";

describe("useAccessor", () => {
const renderAccessorHook = <V>(initialValue?: V) =>
renderHook((value = initialValue) => useAccessor(value));

it("returns a getter and setter if no initial value provided", () => {
const { result, rerender } = renderAccessorHook();
const [getter, setter] = result.current;
expect(getter()).toBeUndefined();
expect(setter).toBeDefined();
setter?.("some value");
expect(getter()).toBe("some value");
rerender("other value");
expect(getter()).toBe("some value");
});

it("returns a getter only if an initial value is provided", () => {
const { result, rerender } = renderAccessorHook("initial value");
const [getter, setter] = result.current;
expect(getter()).toBe("initial value");
expect(setter).toBeUndefined();
setter?.("some value");
expect(getter()).toBe("initial value");
rerender("other value");
expect(getter()).toBe("other value");
});
});

describe("useDispatch", () => {
const mockValue = {
dispatch: async (a: Action<string, string>) => a,
Expand Down

0 comments on commit 6b4dfbb

Please sign in to comment.