Skip to content

Commit

Permalink
fix: cache many components per container
Browse files Browse the repository at this point in the history
The way the cache was set up, we could only have one render
element per test. Which, mind you, is the most common use-case,
but it can create surprises.

Fixes testing-library#205
  • Loading branch information
yanick committed Oct 6, 2022
1 parent 6889d54 commit 373a666
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 6 deletions.
14 changes: 14 additions & 0 deletions src/__tests__/auto-cleanup.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,17 @@ describe('auto-cleanup', () => {
expect(document.body.innerHTML).toEqual('')
})
})

describe('cleanup of two components', () => {
// This just verifies that by importing STL in an
// environment which supports afterEach (like jest)
// we'll get automatic cleanup between tests.
test('first', () => {
render(Comp, { props: { name: 'world' } })
render(Comp, { props: { name: 'universe' } })
})

test('second', () => {
expect(document.body.innerHTML).toEqual('')
})
})
12 changes: 6 additions & 6 deletions src/pure.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
} from '@testing-library/dom'
import { tick } from 'svelte'

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

const svelteComponentOptions = [
Expand Down Expand Up @@ -59,7 +59,7 @@ const render = (
...checkProps(options),
})

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

component.$$.on_destroy.push(() => {
Expand All @@ -79,7 +79,7 @@ const render = (
...checkProps(options),
})

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

component.$$.on_destroy.push(() => {
Expand All @@ -93,16 +93,16 @@ const render = (
}
}

const cleanupAtContainer = (container) => {
const { target, component } = containerCache.get(container)
const cleanupAtContainer = (cached) => {
const { target, component } = cached

if (componentCache.has(component)) component.$destroy()

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

containerCache.delete(container)
containerCache.delete(cached)
}

const cleanup = () => {
Expand Down

0 comments on commit 373a666

Please sign in to comment.