Skip to content

Commit 44f5776

Browse files
author
Philipp Molitor
committed
get 100% test coverage for useScript
1 parent 301b78e commit 44f5776

File tree

2 files changed

+21
-7
lines changed

2 files changed

+21
-7
lines changed

src/hooks/__tests__/useScript.test.tsx

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,24 @@ describe('useScript()', () => {
151151
expect(element).toBeInTheDocument();
152152
});
153153

154+
it('adds the <script> tag again when setting a source again', async () => {
155+
const { result } = renderHook(() => useScript());
156+
157+
const element = document.querySelector('script') as HTMLScriptElement;
158+
159+
expect(element).not.toBeInTheDocument();
160+
161+
act(() => {
162+
result.current[1](scriptUrl);
163+
});
164+
165+
const newElement = document.querySelector(
166+
`script[src="${scriptUrl}"]`
167+
) as HTMLScriptElement;
168+
169+
expect(newElement).toBeInTheDocument();
170+
});
171+
154172
it('removes the <script> tag when setting the source to undefined', async () => {
155173
const { result } = renderHook(() => useScript(scriptUrl));
156174

src/hooks/useScript.ts

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,8 @@ export const useScript = (src?: string): UseScriptValue => {
2525

2626
if (!source) {
2727
setScriptState('unloaded');
28-
return;
29-
}
30-
31-
// if script is not in DOM yet, add it
32-
if (source && !script) {
28+
} else if (source && !script) {
29+
// if script is not in DOM yet, add it
3330
script = document.createElement('script');
3431
script.src = source;
3532
script.async = true;
@@ -50,8 +47,7 @@ export const useScript = (src?: string): UseScriptValue => {
5047
document.body.appendChild(script);
5148
}
5249

53-
// eslint-disable-next-line consistent-return
54-
return () => {
50+
return (): void => {
5551
if (script) script.remove();
5652
};
5753
}, [source]);

0 commit comments

Comments
 (0)