Skip to content
Merged
Changes from 3 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
82 changes: 80 additions & 2 deletions documentation/docs/07-misc/02-testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -160,9 +160,11 @@ export function logger(getValue) {

### Component testing

It is possible to test your components in isolation using Vitest.
It is possible to test your components in isolation, which allows you to render them in a browser (real or simulated), simulate behavior, and make assertions, without spinning up your whole app.

> [!NOTE] Before writing component tests, think about whether you actually need to test the component, or if it's more about the logic _inside_ the component. If so, consider extracting out that logic to test it in isolation, without the overhead of a component
> [!NOTE] Before writing component tests, think about whether you actually need to test the component, or if it's more about the logic _inside_ the component. If so, consider extracting out that logic to test it in isolation, without the overhead of a component.

_With Vitest and jsdom_

To get started, install jsdom (a library that shims DOM APIs):

Expand Down Expand Up @@ -246,6 +248,82 @@ test('Component', async () => {

When writing component tests that involve two-way bindings, context or snippet props, it's best to create a wrapper component for your specific test and interact with that. `@testing-library/svelte` contains some [examples](https://testing-library.com/docs/svelte-testing-library/example).

_With Storybook_
Copy link
Contributor Author

Choose a reason for hiding this comment

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

I'd like to make this a heading, but the level required here, h4, is not styled in the docs site.

If you agree that the h4 is necessary, I'll need some help navigating where to place that style. 😅

Copy link
Member

Choose a reason for hiding this comment

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

alternative would be to move testing out of misc and make it a separate top level category so h3 should work here. This would be a larger change though so waiting for feedback from other svelte team members.


[Storybook](https://storybook.js.org?ref=svelte-docs) is the industry standard for developing and documenting UI components, and it can also be used to test your components. A storybook is made up of [stories](https://storybook.js.org/docs/writing-stories?ref=svelte-docs&renderer=svelte)—isolated examples of your components in different states and with simulated interactions. These stories can also function as [component tests](https://storybook.js.org/docs/writing-tests?ref=svelte-docs&renderer=svelte), with no additional code needed. They're run with Vitest's browser mode, which renders your components in a real browser for the most realistic testing environment.

To get started, first install Storybook ([using Svelte's CLI](/docs/cli/storybook)) in your project if you haven't already:

```sh
npx sv add storybook
```

When prompted, choose the recommended configuration that includes testing features.

If you already have Storybook set up, but are not yet using the testing features, first upgrade to the latest version:

```sh
npx storybook@latest upgrade
```

Then, install and configure Storybook's Vitest addon:

```sh
npx storybook add @storybook/addon-vitest
```

That `add` command will install and register the Vitest addon. It will also inspect your project's Vite and Vitest setup, and install and configure them with sensible defaults, if necessary. You may need to adjust the [configuration](https://storybook.js.org/docs/writing-tests/integrations/vitest-addon?ref=svelte-docs&renderer=svelte#options) to fit your project's needs.

When you run Storybook, you will see a test widget in the bottom of your sidebar, from where you can run your tests. Each story is automatically transformed into a test. The results will be shown in the sidebar and you can debug your tests using Storybook's tools and the browser devtools. You can also integrate [accessibility tests](https://storybook.js.org/docs/writing-tests/accessibility?ref=svelte-docs&renderer=svelte), which will run alongside your component tests.

You can also run those component tests in the terminal (and in CI) using the Vitest CLI.:

```sh
npx vitest --project storybook
```

You can create stories for component variations and test interactions with the [play function](https://storybook.js.org/docs/writing-tests/interaction-testing?ref=svelte-docs&renderer=svelte#writing-interaction-tests), which allows you to simulate behavior and make assertions using the Testing Library and Vitest APIs. Here's an example of two stories that can be tested, one that renders an empty Form component and one that simulates a user filling out the form:

```svelte
/// file: LoginForm.stories.svelte
<script module>
import { defineMeta } from '@storybook/addon-svelte-csf';
import { expect, fn } from 'storybook/test';

import LoginForm from './LoginForm.svelte';

const { Story } = defineMeta({
component: LoginForm,
args: {
// 👇 Pass a mock function to the `onSubmit` prop
onSubmit: fn(),
}
});
</script>

<Story name="Empty Form" />

<Story
name="Filled Form"
play={async ({ args, canvas, userEvent }) => {
// 👇 Simulate a user filling out the form
await userEvent.type(canvas.getByTestId('email'), '[email protected]');
await userEvent.type(canvas.getByTestId('password'), 'a-random-password');
await userEvent.click(canvas.getByRole('button'));

// 👇 Assert that the `onSubmit` function was called
await expect(args.onSubmit).toHaveBeenCalledTimes(1);

// 👇 Assert that the success message is shown
await expect(canvas.getByText('You’re in!')).toBeInTheDocument();
}}
/>
```

When you view that story or run that test in Storybook, you can see each step of the simulated behavior and the assertions made against the component. If anything goes wrong, you can step back-and-forth through the test to pinpoint exactly where the issue occurred.
Copy link
Contributor

Choose a reason for hiding this comment

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

Should we consider a teaser for other SB Test features here?

To learn more about Storybook's mocking, accessibility testing, interactions debugging, and coverage tools, please see the Storybook testing docs.


To learn more about Storybook's mocking, accessibility testing, interactions debugging, and coverage tools, please see the [Storybook testing docs](https://storybook.js.org/docs/writing-tests?ref=svelte-docs&renderer=svelte).

## E2E tests using Playwright

E2E (short for 'end to end') tests allow you to test your full application through the eyes of the user. This section uses [Playwright](https://playwright.dev/) as an example, but you can also use other solutions like [Cypress](https://www.cypress.io/) or [NightwatchJS](https://nightwatchjs.org/).
Expand Down