### Setup and Run with Svelte 5 Source: https://github.com/testing-library/svelte-testing-library/blob/main/CONTRIBUTING.md Install dependencies and run all tests for Svelte version 5. ```shell pnpm run install:5 pnpm run all ``` -------------------------------- ### Setup Project Dependencies and Build Source: https://github.com/testing-library/svelte-testing-library/blob/main/CONTRIBUTING.md Run this command after cloning the repository to install dependencies, build the project, and execute all checks. ```shell pnpm run setup ``` -------------------------------- ### Setup and Run with Svelte 3 (Legacy) Source: https://github.com/testing-library/svelte-testing-library/blob/main/CONTRIBUTING.md Install dependencies and run all legacy tests for Svelte version 3. ```shell pnpm run install:3 pnpm run all:legacy ``` -------------------------------- ### Setup and Run with Svelte 4 (Legacy) Source: https://github.com/testing-library/svelte-testing-library/blob/main/CONTRIBUTING.md Install dependencies and run all legacy tests for Svelte version 4. ```shell pnpm run install:4 pnpm run all:legacy ``` -------------------------------- ### Manual Lifecycle Control with setup and cleanup Source: https://context7.com/testing-library/svelte-testing-library/llms.txt Use setup and cleanup for manual management of the testing environment, especially when auto-cleanup is disabled. setup configures the environment, and cleanup unmounts components and resets configurations. ```js import { cleanup, render, setup } from '@testing-library/svelte' import MyComp from './MyComp.svelte' // Disable auto-cleanup in vitest config: // svelteTesting({ autoCleanup: false }) // Or set env var for Jest: STL_SKIP_AUTO_CLEANUP=1 jest beforeEach(() => { setup() // configures @testing-library/dom's asyncWrapper and eventWrapper for Svelte }) afterEach(async () => { await act() // flush any pending Svelte updates cleanup() // unmounts all components and resets @testing-library/dom config }) test('renders correctly', () => { render(MyComp, { name: 'Test' }) // ... }) ``` -------------------------------- ### setup Source: https://github.com/testing-library/svelte-testing-library/blob/main/packages/svelte-core/README.md Validates options and prepares document elements for rendering a Svelte component. ```APIDOC ## setup Validate options and prepare document elements for rendering. ```ts const { baseElement, container, mountOptions } = setup(componentOptions, setupOptions) ``` ### Parameters - `componentOptions` (Props or partial [`mount` options]) - Options for how the component will be mounted - `setupOptions` ({ baseElement?: HTMLElement }) - Optionally override `baseElement` ### Returns - `baseElement` (HTMLElement) - The base element. Defaults to `document.body`. - `container` (HTMLElement) - The component's immediate parent element. Defaults to a `
` appended to `document.body`. - `mountOptions` ([`mount` options]) - Validated options to pass to `mount`. ``` -------------------------------- ### Setup Component for Testing Source: https://github.com/testing-library/svelte-testing-library/blob/main/packages/svelte-core/README.md Use `setup` to validate options and prepare document elements for rendering your Svelte component during tests. It returns the base element, container, and validated mount options. ```typescript const { baseElement, container, mountOptions } = setup( componentOptions, setupOptions ) ``` -------------------------------- ### Manual Setup and Cleanup in Svelte Testing Library Source: https://github.com/testing-library/svelte-testing-library/blob/main/README.md Demonstrates how to manually call setup and cleanup functions when auto-cleanup is disabled or not provided by the test runner. This is useful for custom test environments. ```javascript import { cleanup, render, setup } from '@testing-library/svelte' // before setup() // test render(/* ... */) // after cleanup() ``` -------------------------------- ### Install @testing-library/svelte Source: https://context7.com/testing-library/svelte-testing-library/llms.txt Install the library as a dev dependency. Recommended peer tools include Vitest, @testing-library/jest-dom, and @testing-library/user-event. ```shell npm install --save-dev @testing-library/svelte # Recommended peer tools npm install --save-dev vitest @testing-library/jest-dom @testing-library/user-event ``` -------------------------------- ### Install Svelte Testing Library Source: https://github.com/testing-library/svelte-testing-library/blob/main/README.md Install the library as a development dependency using npm. This library supports Svelte versions 3, 4, and 5. ```shell npm install --save-dev @testing-library/svelte ``` -------------------------------- ### render Source: https://github.com/testing-library/svelte-testing-library/blob/main/packages/svelte-core/README.md Sets up the document and mounts a Svelte component into it. This is a convenience function that combines setup and mount operations. ```APIDOC ## render ### Description Set up the document and mount a component into that document. ### Signature ```ts const { baseElement, container, component, rerender, unmount } = render( Component, componentOptions, setupOptions ) ``` ### Parameters #### Arguments - **Component** ([Svelte component][svelte-component-docs]) - An imported Svelte component. - **componentOptions** (`Props` or partial [`mount` options][svelte-mount-docs]) - Options for how the component will be mounted. - **setupOptions** (`{ baseElement?: HTMLElement }`) - Optionally override `baseElement`. ### Returns #### Result - **baseElement** (`HTMLElement`) - The base element. Defaults to `document.body`. - **container** (`HTMLElement`) - The component's immediate parent element. Defaults to a `
` appended to `document.body`. - **component** ([component exports][svelte-mount-docs]) - The component's exports from `mount`. - **rerender** (`(props: Partial) => Promise`) - A function to update the component's props. - **unmount** (`() => void`) - A function to unmount the component from the document. ### Notes Calling `render` is equivalent to calling [`setup`](#setup) followed by [`mount`](#mount). ```ts const { baseElement, container, mountOptions } = setup( componentOptions, setupOptions ) const { component, rerender, unmount } = mount(Component, mountOptions) ``` [svelte-component-docs]: https://svelte.dev/docs/svelte-components [svelte-mount-docs]: https://svelte.dev/docs/svelte/imperative-component-api#mount ``` -------------------------------- ### Render Function Equivalency Source: https://github.com/testing-library/svelte-testing-library/blob/main/packages/svelte-core/README.md Illustrates that calling the render function is equivalent to calling setup followed by mount. ```typescript const { baseElement, container, mountOptions } = setup( componentOptions, setupOptions ) const { component, rerender, unmount } = mount(Component, mountOptions) ``` -------------------------------- ### Format Code Source: https://github.com/testing-library/svelte-testing-library/blob/main/CONTRIBUTING.md Run this command to automatically format code and ensure it adheres to the repository's style guide. ```shell pnpm run format ``` -------------------------------- ### Custom Render Function with Query Binding Source: https://github.com/testing-library/svelte-testing-library/blob/main/packages/svelte-core/README.md Example of a custom render function that binds queries to the base element. It includes cleanup logic for tests. ```typescript import { beforeEach } from 'vitest' import * as SvelteCore from '@testing-library/svelte-core' import type { Component, Exports, Rerender, } from '@testing-library/svelte-core/types' import { bindQueries, type Queries } from './bring-your-own-queries.js' beforeEach(() => { SvelteCore.cleanup() }) export interface RenderResult extends Queries { container: HTMLElement component: Exports rerender: Rerender unmount: () => void } export const render = (<0xC2><0xA0>Component: SvelteCore.ComponentImport, options: SvelteCore.ComponentOptions ): RenderResult => { const { baseElement, component, container, rerender, unmount } = SvelteCore.render(Component, options) const queries = bindQueries(baseElement) return { component, container, rerender, unmount, ...queries } } ``` -------------------------------- ### Build Types and Docs Source: https://github.com/testing-library/svelte-testing-library/blob/main/CONTRIBUTING.md Execute this command to build the project's types and documentation. ```shell pnpm run build ``` -------------------------------- ### Run Unit Tests Source: https://github.com/testing-library/svelte-testing-library/blob/main/CONTRIBUTING.md Execute unit tests once. For continuous testing, use the watch mode. ```shell pnpm test ``` -------------------------------- ### Generate Contributor List Source: https://github.com/testing-library/svelte-testing-library/blob/main/CONTRIBUTING.md Run this command to ensure the contributor list in the README is up-to-date. ```shell pnpm run contributors:generate ``` -------------------------------- ### mount Source: https://github.com/testing-library/svelte-testing-library/blob/main/packages/svelte-core/README.md Mounts a Svelte component into the document with specified options. ```APIDOC ## mount Mount a Svelte component into the document. ```ts const { component, unmount, rerender } = mount(Component, mountOptions) ``` ### Parameters - `Component` ([Svelte component]) - An imported Svelte component. - `mountOptions` ([component options]) - Options to pass to Svelte's `mount` function. ### Returns - `component` ([component exports]) - The component's exports from `mount`. - `unmount` (() => void) - Unmount the component from the document. - `rerender` ((props: Partial) => Promise) - Update the component's props. ``` -------------------------------- ### Add a Contributor Source: https://github.com/testing-library/svelte-testing-library/blob/main/CONTRIBUTING.md Use this command to add a new contributor to the README file. ```shell pnpm run contributors:add ``` -------------------------------- ### Configure Vite with svelteTesting Plugin Source: https://context7.com/testing-library/svelte-testing-library/llms.txt The `svelteTesting` Vite plugin configures Vite and Vitest for correct operation with the testing library. It ensures the browser Svelte build is used, adds automatic per-test setup/cleanup, and marks @testing-library/svelte as non-external. ```javascript // vite.config.js import { svelte } from '@sveltejs/vite-plugin-svelte' import { svelteTesting } from '@testing-library/svelte/vite' import { defineConfig } from 'vite' export default defineConfig({ plugins: [ svelte(), svelteTesting({ resolveBrowser: true, // ensure browser Svelte build (default: true) autoCleanup: true, // auto setup/cleanup per test (default: true) noExternal: true, // process STL through vite-plugin-svelte (default: true) }), ], }) ``` -------------------------------- ### Inspect `render` Return Value Source: https://context7.com/testing-library/svelte-testing-library/llms.txt Demonstrates inspecting the return value of the `render` function, including `container`, `baseElement`, `component` bindings, and the `debug` helper. Shows how to use bound DOM queries. ```javascript import { render } from '@testing-library/svelte' import { prettyDOM } from '@testing-library/dom' import { expect, test } from 'vitest' import MyComp from './MyComp.svelte' test('inspect render result', () => { const { container, baseElement, component, debug, getByText, queryByRole, } = render(MyComp, { props: { name: 'Alice' } }) expect(baseElement).toBe(document.body) expect(container.parentElement).toBe(document.body) // Print the rendered HTML to console for debugging debug() debug(container) expect(getByText('Hello Alice')).toBeInTheDocument() }) ``` -------------------------------- ### Global Query Object with screen Source: https://context7.com/testing-library/svelte-testing-library/llms.txt The screen object provides all @testing-library/dom queries pre-bound to document.body. Use it for a single import of query functions. ```js import { render, screen } from '@testing-library/svelte' import { userEvent } from '@testing-library/user-event' import { expect, test } from 'vitest' import LoginForm from './LoginForm.svelte' test('login form submission', async () => { const user = userEvent.setup() const onSubmit = vi.fn() render(LoginForm, { onSubmit }) // All @testing-library/dom queries are available on screen await user.type(screen.getByLabelText('Email'), 'user@example.com') await user.type(screen.getByLabelText('Password'), 'secret') await user.click(screen.getByRole('button', { name: /submit/i })) expect(onSubmit).toHaveBeenCalledWith({ email: 'user@example.com', password: 'secret', }) }) ``` -------------------------------- ### Render Function Signature Source: https://github.com/testing-library/svelte-testing-library/blob/main/packages/svelte-core/README.md Demonstrates the signature of the render function, showing the arguments it accepts and the structure of its return value. ```typescript const { baseElement, container, component, rerender, unmount } = render( Component, componentOptions, setupOptions ) ``` -------------------------------- ### Render Svelte Component and Test Interaction Source: https://context7.com/testing-library/svelte-testing-library/llms.txt Mounts a Svelte component using `render` and interacts with it using `userEvent`. Props can be passed directly or via the full options form. Asserts the initial state and the state after interaction. ```javascript // Greeting.svelte // // // {#if show}

Hello {name}

{/if} import { render, screen } from '@testing-library/svelte' import { userEvent } from '@testing-library/user-event' import { expect, test } from 'vitest' import Greeting from './Greeting.svelte' test('shows greeting after button click', async () => { const user = userEvent.setup() // Shorthand: pass props directly render(Greeting, { name: 'World' }) // Full options form: render(Greeting, { props: { name: 'World' } }) const button = screen.getByRole('button', { name: 'Greet' }) expect(screen.queryByText(/hello/i)).not.toBeInTheDocument() await user.click(button) expect(screen.getByText('Hello World')).toBeInTheDocument() // render also returns container, baseElement, component, rerender, unmount, debug }) ``` -------------------------------- ### Render with Event Handlers Source: https://context7.com/testing-library/svelte-testing-library/llms.txt Pass event handler functions (e.g. `onclick`) directly as props to test component event wiring. Use `vi.fn()` to create mock functions for assertions. ```js import { render, screen } from '@testing-library/svelte' import { userEvent } from '@testing-library/user-event' import { expect, test, vi } from 'vitest' import Button from './Button.svelte' test('calls onclick handler when button is clicked', async () => { const user = userEvent.setup() const onclick = vi.fn() render(Button, { onclick }) await user.click(screen.getByRole('button')) expect(onclick).toHaveBeenCalledOnce() }) ``` -------------------------------- ### Render with Custom Base Element and Target Source: https://context7.com/testing-library/svelte-testing-library/llms.txt Override the mount target and base element for rendering into custom DOM structures. Ensure the custom base element is appended to the document body. ```js import { render, screen } from '@testing-library/svelte' import { expect, test } from 'vitest' import Comp from './Comp.svelte' test('render into a custom target with anchor', () => { const customBase = document.createElement('div') document.body.append(customBase) const target = document.createElement('section') const anchor = document.createElement('footer') customBase.append(target) target.append(anchor) const { baseElement, container } = render( Comp, { props: { name: 'World' }, target, anchor }, { baseElement: customBase } ) expect(baseElement).toBe(customBase) expect(container).toBe(target) // component renders before anchor inside target expect(target.lastChild).toBe(anchor) }) ``` -------------------------------- ### Run Unit Tests in Watch Mode Source: https://github.com/testing-library/svelte-testing-library/blob/main/CONTRIBUTING.md Run unit tests continuously, automatically re-running them when changes are detected. ```shell pnpm run test:watch ``` -------------------------------- ### Mount Svelte Component Source: https://github.com/testing-library/svelte-testing-library/blob/main/packages/svelte-core/README.md Use `mount` to render a Svelte component into the document. It returns the component instance, an `unmount` function, and a `rerender` function for updating props. ```typescript const { component, unmount, rerender } = mount(Component, mountOptions) ``` -------------------------------- ### Lint and Format Checks Source: https://github.com/testing-library/svelte-testing-library/blob/main/CONTRIBUTING.md Use this command to perform lint and format checks without modifying any files. ```shell pnpm run lint ``` -------------------------------- ### Render basic snippet component with test ID Source: https://github.com/testing-library/svelte-testing-library/blob/main/examples/snippets/readme.md For simple snippets, use a wrapper component and dummy children. Setting `data-testid` attributes on children can help when testing slots. ```svelte

{@render children?.()}

``` ```svelte ``` ```js import { render, screen, within } from '@testing-library/svelte' import { expect, test } from 'vitest' import SubjectTest from './basic-snippet.test.svelte' test('basic snippet', () => { render(SubjectTest) const heading = screen.getByRole('heading') const child = within(heading).getByTestId('child') expect(child).toBeInTheDocument() }) ``` -------------------------------- ### Render with Svelte Context Source: https://context7.com/testing-library/svelte-testing-library/llms.txt Provide Svelte context values to the component under test using the `context` option with a `Map`. Ensure the context key matches the one used in the component. ```js import { render, screen } from '@testing-library/svelte' import { expect, test } from 'vitest' import Notifications from './Notifications.svelte' test('renders messages from context', () => { const messages = { get current() { return [ { id: 'abc', text: 'hello' }, { id: 'def', text: 'world' }, ] }, } render(Notifications, { context: new Map([['messages', messages]]), props: { label: 'Notifications' }, }) const status = screen.getByRole('status', { name: 'Notifications' }) expect(status).toHaveTextContent('hello world') }) ``` -------------------------------- ### Testing Bindable Prop with Setters Source: https://github.com/testing-library/svelte-testing-library/blob/main/examples/binds/readme.md A Vitest test case for a Svelte component using `$bindable()` props. It utilizes `userEvent` to simulate user input and verifies the binding by checking the updated prop value via a setter. ```javascript import { render, screen } from '@testing-library/svelte' import { userEvent } from '@testing-library/user-event' import { expect, test } from 'vitest' import Subject from './bind.svelte' test('value binding', async () => { const user = userEvent.setup() let value = '' render(Subject, { get value() { return value }, set value(nextValue) { value = nextValue }, }) const input = screen.getByRole('textbox') await user.type(input, 'hello world') expect(value).toBe('hello world') }) ``` -------------------------------- ### Svelte Component Test: Greeting on Click Source: https://github.com/testing-library/svelte-testing-library/blob/main/examples/basic/readme.md Tests that the greeting message appears after the button is clicked. Simulates a user click using userEvent and asserts the greeting's presence. ```javascript import { render, screen } from '@testing-library/svelte' import { userEvent } from '@testing-library/user-event' import { expect, test } from 'vitest' import Subject from './basic.svelte' test('greeting appears on click', async () => { const user = userEvent.setup() render(Subject, { name: 'World' }) const button = screen.getByRole('button') await user.click(button) const greeting = screen.getByText(/hello world/iu) expect(greeting).toBeInTheDocument() }) ``` -------------------------------- ### Svelte Component with Click Handler Source: https://github.com/testing-library/svelte-testing-library/blob/main/examples/events/readme.md A basic Svelte component with a button that accepts an `onclick` prop. ```svelte ``` -------------------------------- ### Add svelteTesting Plugin to Vite Config Source: https://github.com/testing-library/svelte-testing-library/blob/main/README.md Integrate the svelteTesting plugin into your Vite configuration to enable Svelte component testing. This is a required step for using the library with Vite. ```diff // vite.config.js import { svelte } from '@sveltejs/vite-plugin-svelte' + import { svelteTesting } from '@testing-library/svelte/vite' export default defineConfig({ plugins: [ svelte(), + svelteTesting(), ] }); ``` -------------------------------- ### Svelte Component Test: Initial State Source: https://github.com/testing-library/svelte-testing-library/blob/main/examples/basic/readme.md Tests the initial state of the Svelte component, ensuring the greeting is not displayed before the button is clicked. Uses render, screen, and expect. ```javascript import { render, screen } from '@testing-library/svelte' import { userEvent } from '@testing-library/user-event' import { expect, test } from 'vitest' import Subject from './basic.svelte' test('no initial greeting', () => { render(Subject, { name: 'World' }) const button = screen.getByRole('button', { name: 'Greet' }) const greeting = screen.queryByText(/hello/iu) expect(button).toBeInTheDocument() expect(greeting).not.toBeInTheDocument() }) ``` -------------------------------- ### Svelte Component with Bindable Prop Source: https://github.com/testing-library/svelte-testing-library/blob/main/examples/binds/readme.md A Svelte component demonstrating the use of a `$bindable()` prop for two-way data binding with an input element. ```svelte ``` -------------------------------- ### Svelte Component with Props and State Source: https://github.com/testing-library/svelte-testing-library/blob/main/examples/basic/readme.md A Svelte component that accepts a 'name' prop and toggles a greeting message on button click. This is the component under test. ```svelte {#if showGreeting}

Hello {name}

{/if} ``` -------------------------------- ### Test Key-Based Context in Svelte Source: https://github.com/testing-library/svelte-testing-library/blob/main/examples/contexts/readme.md Tests a Svelte component that consumes context using a key. It provides the context data via a `Map` in the `render` function's `context` option. ```javascript import { render, screen } from '@testing-library/svelte' import { expect, test } from 'vitest' import Subject from './context.svelte' test('notifications with messages from context', () => { const messages = { get current() { return [ { id: 'abc', text: 'hello' }, { id: 'def', text: 'world' }, ] }, } render(Subject, { context: new Map([['messages', messages]]), props: { label: 'Notifications' }, }) const status = screen.getByRole('status', { name: 'Notifications' }) expect(status).toHaveTextContent('hello world') }) ``` -------------------------------- ### cleanup Source: https://github.com/testing-library/svelte-testing-library/blob/main/packages/svelte-core/README.md Cleans up rendered components and any added elements. Should be called after tests are completed. ```APIDOC ## cleanup Cleanup rendered components and added elements. Call this when your tests are over. ```ts cleanup() ``` ``` -------------------------------- ### Render with Two-Way Bindings Source: https://context7.com/testing-library/svelte-testing-library/llms.txt Test Svelte `bind:` directives by passing getter/setter objects as props. The external value will be updated when the input changes. ```js import { render, screen } from '@testing-library/svelte' import { userEvent } from '@testing-library/user-event' import { expect, test } from 'vitest' import BindInput from './BindInput.svelte' test('two-way binding updates external value', async () => { const user = userEvent.setup() let value = '' render(BindInput, { get value() { return value }, set value(next) { value = next }, }) const input = screen.getByRole('textbox') await user.type(input, 'hello world') expect(value).toBe('hello world') }) ``` -------------------------------- ### addCleanupTask Source: https://github.com/testing-library/svelte-testing-library/blob/main/packages/svelte-core/README.md Adds a custom task to be executed when the main `cleanup` function is called. ```APIDOC ## addCleanupTask Add a custom cleanup task to be called with `cleanup()` ```ts addCleanupTask(() => { // ...reset something }) ``` ``` -------------------------------- ### Test Svelte Component Event Handling with Vitest Source: https://github.com/testing-library/svelte-testing-library/blob/main/examples/events/readme.md Tests a Svelte component's button click event using `@testing-library/svelte` and `@testing-library/user-event`. It uses `vi.fn()` from Vitest to spy on the `onclick` handler and asserts that it has been called once. ```javascript import { render, screen } from '@testing-library/svelte' import { userEvent } from '@testing-library/user-event' import { expect, test, vi } from 'vitest' import Subject from './event.svelte' test('onclick event', async () => { const user = userEvent.setup() const onclick = vi.fn() render(Subject, { onclick }) const button = screen.getByRole('button') await user.click(button) expect(onclick).toHaveBeenCalledOnce() }) ``` -------------------------------- ### Test complex snippet with createRawSnippet Source: https://github.com/testing-library/svelte-testing-library/blob/main/examples/snippets/readme.md For complex snippets where argument checking is needed, use Svelte's `createRawSnippet` API. This allows you to define how the snippet renders and what arguments it receives. ```svelte

{@render message?.(greeting)}

``` ```js import { render, screen } from '@testing-library/svelte' import { createRawSnippet } from 'svelte' import { expect, test } from 'vitest' import Subject from './complex-snippet.svelte' test('renders greeting in message snippet', () => { render(Subject, { name: 'Alice', message: createRawSnippet((greeting) => ({ render: () => `${greeting()}`, })), }) const message = screen.getByTestId('message') expect(message).toHaveTextContent('Hello, Alice!') }) ``` -------------------------------- ### Render with Snippets (Svelte 5) Source: https://context7.com/testing-library/svelte-testing-library/llms.txt To pass snippet children to a Svelte 5 component under test, create a wrapper `.test.svelte` component that composes the component with its snippet content. ```svelte ``` ```js import { render, screen, within } from '@testing-library/svelte' import { expect, test } from 'vitest' import SubjectTest from './BasicSnippet.test.svelte' test('renders snippet children', () => { render(SubjectTest) const heading = screen.getByRole('heading') const child = within(heading).getByTestId('child') expect(child).toBeInTheDocument() }) ``` -------------------------------- ### Consume Key-Based Context in Svelte Component Source: https://github.com/testing-library/svelte-testing-library/blob/main/examples/contexts/readme.md Renders a list of messages obtained from a context identified by the key 'messages'. It iterates over `messages.current` and displays each message's text. ```svelte
{#each messages.current as message (message.id)}

{message.text}


{/each}
``` -------------------------------- ### Fire DOM Events with fireEvent Source: https://context7.com/testing-library/svelte-testing-library/llms.txt Use fireEvent to simulate DOM events. It automatically waits for Svelte to process reactive state changes after an event. Always await fireEvent methods. ```js import { fireEvent, render, screen } from '@testing-library/svelte' import { expect, test } from 'vitest' import Counter from './Counter.svelte' test('increments counter on click', async () => { render(Counter, { props: { name: 'World' } }) const button = screen.getByText('Button') // fireEvent methods return Promises — always await them await fireEvent.click(button) expect(button).toHaveTextContent('Button Clicked') // Or fire a raw event await fireEvent(button, new MouseEvent('click', { bubbles: true, cancelable: true })) }) ``` -------------------------------- ### Define Type-Safe Context in TypeScript Source: https://github.com/testing-library/svelte-testing-library/blob/main/examples/contexts/readme.md Defines interfaces for context data and creates a type-safe context using `createContext`. Requires `svelte>=5.50.0` for setting context in wrapper functions. ```typescript import { createContext } from 'svelte' export interface Message { id: string text: string } export interface MessagesContext { current: Message[] } export const [getMessagesContext, setMessagesContext] = createContext() ``` -------------------------------- ### Disable Auto-Cleanup in svelteTesting Plugin Source: https://github.com/testing-library/svelte-testing-library/blob/main/README.md Configure the svelteTesting Vite plugin to disable automatic cleanup of the test environment before and after each test. Set the `autoCleanup` option to `false`. ```javascript svelteTesting({ autoCleanup: false }) ``` -------------------------------- ### TypeScript Typed render and rerender Source: https://context7.com/testing-library/svelte-testing-library/llms.txt Leverage full TypeScript types for render and rerender, which adapt to Svelte versions and provide static prop validation. Component exports are also correctly inferred. ```ts import { render } from '@testing-library/svelte' import { expectTypeOf, test } from 'vitest' import Component from './TypedComponent.svelte' // Component has props: { name: string, count: number } // Component exports: { hello: string } test('render types are correct', async () => { const result = render(Component, { name: 'Alice', count: 42 }) // component exports are typed expectTypeOf(result.component).toMatchTypeOf<{ hello: string }>() // rerender accepts partial props await result.rerender({ name: 'Bob' }) await result.rerender({ count: 0 }) // TypeScript error: name must be a string // render(Component, { name: 42 }) // @ts-expect-error }) ``` -------------------------------- ### Test Type-Safe Context in Svelte Source: https://github.com/testing-library/svelte-testing-library/blob/main/examples/contexts/readme.md Tests a Svelte component that consumes type-safe context. It sets up mock context data and renders the component using a wrapper function that provides the context. ```typescript import { render, screen } from '@testing-library/svelte' import { expect, test } from 'vitest' import { type MessagesContext, setMessagesContext } from './typesafe-context.js' import Subject from './typesafe-context.svelte' test('notifications with messages from context', () => { const messages: MessagesContext = { get current() { return [ { id: 'abc', text: 'hello' }, { id: 'def', text: 'world' }, ] }, } const Wrapper: typeof Subject = (...args) => { setMessagesContext(messages) return Subject(...args) } render(Wrapper, { label: 'Notifications' }) const status = screen.getByRole('status', { name: 'Notifications' }) expect(status).toHaveTextContent('hello world') }) ``` -------------------------------- ### Unmount Component Source: https://context7.com/testing-library/svelte-testing-library/llms.txt Manually unmount a component and remove it from the DOM. This is useful for cleanup after tests. ```js import { render, screen } from '@testing-library/svelte' import { expect, test } from 'vitest' import Mounter from './Mounter.svelte' test('component is removed on unmount', () => { const { unmount } = render(Mounter) expect(screen.getByRole('button')).toBeInTheDocument() unmount() expect(screen.queryByRole('button')).not.toBeInTheDocument() }) ``` -------------------------------- ### Add Custom Cleanup Task Source: https://github.com/testing-library/svelte-testing-library/blob/main/packages/svelte-core/README.md Use `addCleanupTask` to register a custom function that will be executed when `cleanup()` is called. This is useful for resetting global state or other side effects. ```typescript addCleanupTask(() => { // ...reset something }) ``` -------------------------------- ### Cleanup Rendered Components Source: https://github.com/testing-library/svelte-testing-library/blob/main/packages/svelte-core/README.md Call `cleanup` to remove all rendered components and elements added to the document by the testing library. This should be called after your tests are complete. ```typescript cleanup() ``` -------------------------------- ### Flush Svelte State Updates with act Source: https://context7.com/testing-library/svelte-testing-library/llms.txt The act utility wraps functions to ensure all pending Svelte reactive state updates are flushed to the DOM. It supports both synchronous and asynchronous callbacks. ```js import { act, render, screen } from '@testing-library/svelte' import { expect, test } from 'vitest' import Counter from './Counter.svelte' test('manually flush state updates with act', async () => { render(Counter) const button = screen.getByText('Button') // Synchronous interaction wrapped in act await act(() => { button.click() }) expect(button).toHaveTextContent('Button Clicked') // Async callback also supported await act(async () => { await new Promise((r) => setTimeout(r, 10)) button.click() }) }) ``` -------------------------------- ### Rerender Component with Updated Props Source: https://context7.com/testing-library/svelte-testing-library/llms.txt Update the component's props and await Svelte's reactive updates to flush to the DOM. Partial props updates are allowed. ```js import { render, screen } from '@testing-library/svelte' import { expect, test } from 'vitest' import Greeting from './Greeting.svelte' test('rerender with new props', async () => { const { rerender } = render(Greeting, { name: 'Alice' }) expect(screen.getByText('Hello Alice')).toBeInTheDocument() // Pass only the props you want to update (partial props allowed) await rerender({ name: 'Bob' }) expect(screen.getByText('Hello Bob')).toBeInTheDocument() expect(screen.queryByText('Hello Alice')).not.toBeInTheDocument() }) ``` -------------------------------- ### Consume Type-Safe Context in Svelte Component Source: https://github.com/testing-library/svelte-testing-library/blob/main/examples/contexts/readme.md Renders a list of messages obtained from a type-safe context. It iterates over `messages.current` and displays each message's text. ```svelte
{#each messages.current as message (message.id)}

{message.text}


{/each}
``` -------------------------------- ### removeCleanupTask Source: https://github.com/testing-library/svelte-testing-library/blob/main/packages/svelte-core/README.md Removes a previously added custom cleanup task. ```APIDOC ## removeCleanupTask Remove a cleanup task from `cleanup()`. Useful if a cleanup task can only be run once and may be run outside of `cleanup` ```ts const customCleanup = () => { // ...reset something } addCleanupTask(customCleanup) const manuallyCleanupEarly = () => { customCleanup() removeCleanupTask(customCleanup) } ``` ``` -------------------------------- ### Svelte Component without Bindable Prop Source: https://github.com/testing-library/svelte-testing-library/blob/main/examples/binds/readme.md An alternative Svelte component structure that avoids two-way binding. It uses a value prop for downward data flow and a callback prop (`onInput`) for upward event handling. ```svelte ``` -------------------------------- ### Disable Auto-Cleanup with Environment Variable Source: https://github.com/testing-library/svelte-testing-library/blob/main/README.md Disable auto-cleanup for Jest and other frameworks that use global test hooks by setting the `STL_SKIP_AUTO_CLEANUP` environment variable to `1`. ```shell STL_SKIP_AUTO_CLEANUP=1 jest ``` -------------------------------- ### Remove Custom Cleanup Task Source: https://github.com/testing-library/svelte-testing-library/blob/main/packages/svelte-core/README.md Use `removeCleanupTask` to unregister a previously added cleanup task. This is useful if a task should only run once or be manually triggered. ```typescript const customCleanup = () => { // ...reset something } addCleanupTask(customCleanup) const manuallyCleanupEarly = () => { customCleanup() removeCleanupTask(customCleanup) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.