0

I have a custom hook that takes a product id and toggles with value (boolean) and toggle as the returns. I'm trying to write a unit test for it, following the example here, but I'm getting TypeScript type-mismatch errors (the example I'm following isn't typescripted).

Custom Hook:

export default function useToggle(id: number): [boolean, () => void] {
  const [value, setValue] = React.useState(false);

  useEffect(() => {
    try {
      const data = localStorage.getItem(ITEMS);
      const all = data ? JSON.parse(data) : {};
      setValue(!!all[id]);
    } catch (error) {
      console.error('items localStorage get error', error);
      setValue(false);
      localStorage.removeItem(ITEMS);
    }
  }, [id]);

  function toggle() {
    try {
      const data = localStorage.getItem(ITEMS);
      const all = data ? JSON?.parse(data) : {};
      all[id] = !all[id];
      localStorage.setItem(ITEMS, JSON.stringify(all));

      setValue(v => !v);
    } catch (error) {
      console.error('items localStorage set error', error);
    }
  }

  return [value, toggle];
}

Test in progress:


describe('useToggle', () => {
  it('returns value and toggle', () => {
    const { result } = renderHook(() => useToggle(1));
    const { value, toggle }: [boolean, () => void] = result.current;

    expect(value).toBe(false);
    expect(setValue).toBeDefined();

  });
});

Error: Where I'm defining value and toggle, I'm getting Property 'value' does not exist on type '[boolean, () => void]'. and Property 'toggle' does not exist on type '[boolean, () => void]'.

Am I setting up the type definition incorrectly or is something else going wrong? Any guidance would be appreciated. Thanks!

1 Answer 1

1

You are returning an array. Therefor you have to destruct using [ value, toggleLike, toggleLike] and not { value, toggleLike}.


describe('useLikes', () => {
  it('returns value and toggleLike', () => {
    const { result } = renderHook(() => useLikes(1));
    const [ value, toggleLike ]: [boolean, () => void] = result.current;

    expect(value).toBe(false);
    expect(setValue).toBeDefined();

  });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.