score:2

A good approach would be testing the component itself, that already contains the hook.

In case you consider that the hook needs to be test without the component, you can use @testing-library/react-hooks package, something like:

const useFirstHook = (shouldThrow = false) => {
  // throw onmount
  useEffect(() => {
    if (shouldThrow) throw new Error('my custom error is thrown');
  }, [shouldThrow]);

  return {
    test1: 'I am test 1'
  };
};

describe('useFirstHook', () => {
  it('should not throw', () => {
    const { result } = renderHook(() => useFirstHook(false));
    expect(result.current.test1).toEqual('I am test 1');
  });

  it('should throw', () => {
    try {
      const { result } = renderHook(() => useFirstHook(true));
      expect(result.current).toBe(undefined);
    } catch (err) {
      expect(err).toEqual(Error('my custom error is thrown'));
    }
  });
});

Related Query

More Query from same tag