Skip to content

Commit

Permalink
feat(uselazy): make use of "handleThrow"
Browse files Browse the repository at this point in the history
handle exception thrown from dynamic import and test properly when this happens
  • Loading branch information
aneurysmjs committed Oct 27, 2019
1 parent c00aeff commit 19de1a2
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
17 changes: 17 additions & 0 deletions src/__test__/useLazy.test.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/ban-ts-ignore */
import { renderHook } from '@testing-library/react-hooks';

import useLazy from '../useLazy';
Expand Down Expand Up @@ -28,4 +29,20 @@ describe('LazyComponent', () => {
expect(typeof result.current).toBe('function');
expect(handleFinally).toHaveBeenCalledTimes(1);
});
it('should throw', async () => {
// @ts-ignore - just for testing purposes
type WrongModule = typeof import('./wrong/Example');
// @ts-ignore - just for testing purposes
const wrongModule = (): WrongModule => import('./wrong/Example'); // eslint-disable-line import/no-unresolved

const { result, waitForNextUpdate } = renderHook(() => useLazy(wrongModule, true));

await waitForNextUpdate();

expect(() => {
expect(result.current).not.toBe(undefined);
}).toThrow(
Error(`useLazy Error: Cannot find module './wrong/Example' from 'useLazy.test.tsx'`),
);
});
});
6 changes: 4 additions & 2 deletions src/useLazy.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { useState, useEffect } from 'react';

import handleThrow from './utils/handleThrow';

function useLazy<P>(
getModule: () => Promise<{ default: () => P }>,
cond = false,
Expand All @@ -16,15 +18,15 @@ function useLazy<P>(
const module = await getModule();
setAsyncModule(() => module.default);
} catch (err) {
throw new Error(`useLazy error: ${err}`);
setAsyncModule(err);
} finally {
onFynally();
}
})();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [cond]);

return AsyncModule;
return handleThrow(AsyncModule);
}

export default useLazy;

0 comments on commit 19de1a2

Please sign in to comment.