Skip to content

Commit

Permalink
fix(useScriptTag): unload should remove script tag (vitest-dev#1114)
Browse files Browse the repository at this point in the history
  • Loading branch information
coolhome committed Dec 31, 2021
1 parent cb1654b commit 970fe23
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 3 deletions.
59 changes: 59 additions & 0 deletions packages/core/useScriptTag/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,33 @@ describe('useScriptTag', () => {
expect(scriptTagElement()).toBeInstanceOf(HTMLScriptElement)
})

it('should re-use the same src for multiple loads', async() => {
const addChildListener = vitest.spyOn(document.head, 'appendChild')

expect(addChildListener).not.toBeCalled()

expect(scriptTagElement()).toBeNull()

const vm = useSetup(() => {
const script1 = useScriptTag(src, () => {}, { immediate: false, manual: true })
const script2 = useScriptTag(src, () => {}, { immediate: false, manual: true })

return {
script1,
script2,
}
})

await vm.script1.load(false)
await vm.script2.load(false)

expect(vm.script1.scriptTag.value).not.toBeNull()
expect(vm.script2.scriptTag.value).not.toBeNull()

expect(addChildListener).toBeCalledTimes(1)
expect(scriptTagElement()).toBeInstanceOf(HTMLScriptElement)
})

it('should remove script tag on unmount', async() => {
const removeChildListener = vitest.spyOn(document.head, 'removeChild')

Expand Down Expand Up @@ -90,4 +117,36 @@ describe('useScriptTag', () => {

expect(vm.scriptTag).toBeNull()
})

it('should remove script tag on unload call after multiple loads', async() => {
const removeChildListener = vitest.spyOn(document.head, 'removeChild')

expect(removeChildListener).not.toBeCalled()

expect(scriptTagElement()).toBeNull()

const vm = useSetup(() => {
const script1 = useScriptTag(src, () => {}, { immediate: false, manual: true })
const script2 = useScriptTag(src, () => {}, { immediate: false, manual: true })

return {
script1,
script2,
}
})

// Multiple Loads
await vm.script1.load(false)
await vm.script2.load(false)

expect(scriptTagElement()).toBeInstanceOf(HTMLScriptElement)

vm.script1.unload()
vm.script2.unload()

expect(vm.script1.scriptTag.value).toBeNull()
expect(vm.script2.scriptTag.value).toBeNull()
expect(removeChildListener).toBeCalledTimes(1)
expect(scriptTagElement()).toBeNull()
})
})
8 changes: 5 additions & 3 deletions packages/core/useScriptTag/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,10 +156,12 @@ export function useScriptTag(

_promise = null

if (scriptTag.value) {
document.head.removeChild(scriptTag.value)
if (scriptTag.value)
scriptTag.value = null
}

const el = document.querySelector(`script[src="${src}"]`) as HTMLScriptElement
if (el)
document.head.removeChild(el)
}

if (immediate && !manual)
Expand Down

0 comments on commit 970fe23

Please sign in to comment.