Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

262
Views
Unit Testing Custom React Hooks in TypeScript using Jest and @testing-library/react-hooks

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!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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();

  });
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!