Skip to content

fix: remove DOM elements even if component creation fails #314

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion src/__tests__/__snapshots__/render.test.js.snap
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ exports[`render > should accept svelte component options 1`] = `
<button>
Button
</button>
<!--&lt;Comp&gt;-->
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This snapshot removal due to disabling HMR in our test suite

<div />
</div>
</body>
Expand Down
30 changes: 30 additions & 0 deletions src/__tests__/cleanup.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { describe, expect, test, vi } from 'vitest'

import { cleanup, render } from '..'
import Mounter from './fixtures/Mounter.svelte'

const onMounted = vi.fn()
const onDestroyed = vi.fn()
const renderSubject = () => render(Mounter, { onMounted, onDestroyed })

describe('cleanup', () => {
test('cleanup unmounts component and deletes element', () => {
renderSubject()

cleanup()

expect(onDestroyed).toHaveBeenCalledOnce()
expect(document.body).toBeEmptyDOMElement()
})

test('cleanup handles unexpected errors during mount', () => {
onMounted.mockImplementation(() => {
throw new Error('oh no!')
})

expect(renderSubject).toThrowError()
cleanup()

expect(document.body).toBeEmptyDOMElement()
})
})
2 changes: 1 addition & 1 deletion src/__tests__/fixtures/Mounter.svelte
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<script>
import { onDestroy,onMount } from 'svelte'
import { onDestroy, onMount } from 'svelte'

export let onMounted
export let onDestroyed
Expand Down
68 changes: 33 additions & 35 deletions src/pure.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import {
fireEvent as dtlFireEvent,
getQueriesForElement,
prettyDOM
prettyDOM,
} from '@testing-library/dom'
import { tick } from 'svelte'

const containerCache = new Set()
const targetCache = new Set()
const componentCache = new Set()

const svelteComponentOptions = [
Expand All @@ -14,7 +14,7 @@ const svelteComponentOptions = [
'props',
'hydrate',
'intro',
'context'
'context',
]

const render = (
Expand All @@ -24,6 +24,7 @@ const render = (
) => {
container = container || document.body
target = target || container.appendChild(document.createElement('div'))
targetCache.add(target)

const ComponentConstructor = Component.default || Component

Expand Down Expand Up @@ -54,59 +55,56 @@ const render = (
return { props: options }
}

let component = new ComponentConstructor({
target,
...checkProps(options)
})
const renderComponent = (options) => {
const component = new ComponentConstructor({
target,
...checkProps(options),
})

containerCache.add({ container, target, component })
componentCache.add(component)
componentCache.add(component)
component.$$.on_destroy.push(() => {
componentCache.delete(component)
})

component.$$.on_destroy.push(() => {
componentCache.delete(component)
})
return component
}

let component = renderComponent(options)

return {
container,
component,
debug: (el = container) => console.log(prettyDOM(el)),
rerender: (options) => {
if (componentCache.has(component)) component.$destroy()

// eslint-disable-next-line no-new
component = new ComponentConstructor({
target,
...checkProps(options)
})

containerCache.add({ container, target, component })
componentCache.add(component)

component.$$.on_destroy.push(() => {
componentCache.delete(component)
})
cleanupComponent(component)
component = renderComponent(options)
},
unmount: () => {
if (componentCache.has(component)) component.$destroy()
cleanupComponent(component)
},
...getQueriesForElement(container, queries)
...getQueriesForElement(container, queries),
}
}

const cleanupAtContainer = (cached) => {
const { target, component } = cached
const cleanupComponent = (component) => {
const inCache = componentCache.delete(component)

if (componentCache.has(component)) component.$destroy()
if (inCache) {
component.$destroy()
}
}

if (target.parentNode === document.body) {
const cleanupTarget = (target) => {
const inCache = targetCache.delete(target)

if (inCache && target.parentNode === document.body) {
document.body.removeChild(target)
}

containerCache.delete(cached)
}

const cleanup = () => {
Array.from(containerCache.keys()).forEach(cleanupAtContainer)
componentCache.forEach(cleanupComponent)
targetCache.forEach(cleanupTarget)
}

const act = async (fn) => {
Expand Down
2 changes: 1 addition & 1 deletion vite.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { defineConfig } from 'vite'

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => ({
plugins: [svelte()],
plugins: [svelte({ hot: false })],
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I disabled HMR because with it enabled, the new test that throws an error in onMount logs a warning message about "full reload required," which doesn't make sense for a test suite.

I think there's something here to add to the documented setup, but vite-plugin-svelte's default setting for hot is more complicated than true/false, so I still need to test to find a good general setting for real projects

resolve: {
// Ensure `browser` exports are used in tests
// Vitest prefers modules' `node` export by default
Expand Down