Skip to content
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

fix!: Rerender to only update props of component without destroying it #210

Merged
merged 7 commits into from
Feb 12, 2024
Merged
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
15 changes: 15 additions & 0 deletions src/__tests__/fixtures/Rerender.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<script>
import { getContext, onMount } from 'svelte'

export let name

const mountCounter = getContext('mountCounter')

onMount(() => {
mountCounter.update((i) => i + 1)
})
</script>

<h1 data-testid="test">Hello {name}!</h1>

<div data-testid="mount-counter">{$mountCounter}</div>
50 changes: 25 additions & 25 deletions src/__tests__/rerender.test.js
Original file line number Diff line number Diff line change
@@ -1,38 +1,38 @@
/**
* @jest-environment jsdom
*/
import { describe, expect, test } from 'vitest'
import { expect, test, vi } from 'vitest'
import { writable } from 'svelte/store'

import { render } from '..'
import Comp from './fixtures/Comp.svelte'
import { render, waitFor } from '..'
import Comp from './fixtures/Rerender.svelte'

describe('rerender', () => {
test('mounts new component successfully', () => {
const { container, rerender } = render(Comp, { props: { name: 'World 1' } })
const mountCounter = writable(0)

expect(container.firstChild).toHaveTextContent('Hello World 1!')
rerender({ props: { name: 'World 2' } })
expect(container.firstChild).toHaveTextContent('Hello World 2!')
test('mounts new component successfully', async () => {
const { getByTestId, rerender } = render(Comp, {
props: { name: 'World 1' },
context: new Map(Object.entries({ mountCounter })),
})

test('destroys old component', () => {
let isDestroyed
const expectToRender = (content) =>
waitFor(() => {
expect(getByTestId('test')).toHaveTextContent(content)
expect(getByTestId('mount-counter')).toHaveTextContent('1')
})

const { rerender, component } = render(Comp, { props: { name: '' } })
await expectToRender('Hello World 1!')

component.$$.on_destroy.push(() => {
isDestroyed = true
})
rerender({ props: { name: '' } })
expect(isDestroyed).toBeTruthy()
})
console.warn = vi.fn()

test('destroys old components on multiple rerenders', () => {
const { rerender, queryByText } = render(Comp, { props: { name: 'Neil' } })
rerender({ props: { name: 'World 2' } })
await expectToRender('Hello World 2!')

rerender({ props: { name: 'Alex' } })
expect(queryByText('Hello Neil!')).not.toBeInTheDocument()
rerender({ props: { name: 'Geddy' } })
expect(queryByText('Hello Alex!')).not.toBeInTheDocument()
})
expect(console.warn).toHaveBeenCalled()

console.warn.mockClear()
rerender({ name: 'World 3' })
await expectToRender('Hello World 3!')

expect(console.warn).not.toHaveBeenCalled()
})
32 changes: 13 additions & 19 deletions src/pure.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {
fireEvent as dtlFireEvent,
getQueriesForElement,
prettyDOM
prettyDOM,
} from '@testing-library/dom'
import { tick } from 'svelte'

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

const render = (
Expand Down Expand Up @@ -56,7 +56,7 @@ const render = (

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

containerCache.add({ container, target, component })
Expand All @@ -70,26 +70,20 @@ const render = (
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)
})
rerender: async (props) => {
if (props.props) {
console.warn(
'rerender({ props: {...} }) deprecated, use rerender({...}) instead'
)
props = props.props
}
component.$set(props)
await tick()
},
unmount: () => {
if (componentCache.has(component)) component.$destroy()
},
...getQueriesForElement(container, queries)
...getQueriesForElement(container, queries),
}
}

Expand Down
45 changes: 34 additions & 11 deletions types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,42 @@
// Project: https://github.com/testing-library/svelte-testing-library
// Definitions by: Rahim Alwer <https://github.com/mihar-22>

import {BoundFunction, EventType,Queries, queries} from '@testing-library/dom'
import { ComponentConstructorOptions,ComponentProps, SvelteComponent } from 'svelte'
import {
BoundFunction,
EventType,
Queries,
queries,
} from '@testing-library/dom'
import {
ComponentConstructorOptions,
ComponentProps,
SvelteComponent,
} from 'svelte'

export * from '@testing-library/dom'

type SvelteComponentOptions<C extends SvelteComponent> = ComponentProps<C> | Pick<ComponentConstructorOptions<ComponentProps<C>>, "anchor" | "props" | "hydrate" | "intro" | "context">
type SvelteComponentOptions<C extends SvelteComponent> =
| ComponentProps<C>
| Pick<
ComponentConstructorOptions<ComponentProps<C>>,
'anchor' | 'props' | 'hydrate' | 'intro' | 'context'
>

type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>

type Constructor<T> = new (...args: any[]) => T;
type Constructor<T> = new (...args: any[]) => T

/**
* Render a Component into the Document.
*/
export type RenderResult<C extends SvelteComponent, Q extends Queries = typeof queries> = {
export type RenderResult<
C extends SvelteComponent,
Q extends Queries = typeof queries,
> = {
container: HTMLElement
component: C
debug: (el?: HTMLElement | DocumentFragment) => void
rerender: (options: SvelteComponentOptions<C>) => void
rerender: (props: ComponentProps<C>) => Promise<void>
unmount: () => void
} & { [P in keyof Q]: BoundFunction<Q[P]> }

Expand All @@ -38,7 +55,7 @@ export function render<C extends SvelteComponent>(
export function render<C extends SvelteComponent, Q extends Queries>(
component: Constructor<C>,
componentOptions?: SvelteComponentOptions<C>,
renderOptions?: RenderOptions<Q>,
renderOptions?: RenderOptions<Q>
): RenderResult<C, Q>

/**
Expand All @@ -50,13 +67,19 @@ export function cleanup(): void
* Fires DOM events on an element provided by @testing-library/dom. Since Svelte needs to flush
* pending state changes via `tick`, these methods have been override and now return a promise.
*/
export type FireFunction = (element: Document | Element | Window, event: Event) => Promise<boolean>;
export type FireFunction = (
element: Document | Element | Window,
event: Event
) => Promise<boolean>

export type FireObject = {
[K in EventType]: (element: Document | Element | Window, options?: {}) => Promise<boolean>;
};
[K in EventType]: (
element: Document | Element | Window,
options?: {}
) => Promise<boolean>
}

export const fireEvent: FireFunction & FireObject;
export const fireEvent: FireFunction & FireObject

/**
* Calls a function and notifies Svelte to flush any pending state changes.
Expand Down
Loading