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!