Svelte Testing Library: Test Components Like a User
Test Svelte components like a user would use them. Svelte Testing Library interacts with the rendered DOM, not internal state, to verify behavior. This avoids brittle tests tied to implementation.
WHY IT EXISTS Many component tests break on simple refactors because they test implementation details. You want tests that verify your component works for a user, giving you confidence to ship, without being tightly coupled to the code's internal structure. Svelte Testing Library was created to encourage this style of testing.
THE MENTAL MODEL The library's guiding principle is: "The more your tests resemble the way your software is used, the more confidence they can give you." Instead of grabbing a component instance and checking its internal state, you interact with the rendered DOM, just like a user. You find buttons by their text, fill inputs by their labels, and check for results a user would see.
HOW IT WORKS Svelte Testing Library is a lightweight utility built on top of DOM Testing Library. You use its render function to mount a component. Then, you use its queries (like getByText, getByRole) to find elements on the page. To simulate user behavior, you use fireEvent to click buttons or type in fields. Finally, you use your test runner's assertions (like Jest's or Vitest's expect) to verify the DOM changed as expected.
WHEN TO USE IT Use it with a test runner (like Vitest or Jest) to write unit and integration tests for your Svelte components. It's perfect for verifying user flows: does clicking a button show a modal? Does submitting a form display a success message? It ensures your components are accessible and function correctly from the user's perspective.
WHEN NOT TO USE IT This library is not a test runner or a full end-to-end testing framework. You still need to choose and configure a runner like Vitest or Jest. For testing complex, multi-page user journeys that involve a real browser and backend, you would typically use a tool like Cypress or Playwright, although those tools often adopt the same user-centric philosophy.
ONE CANONICAL EXAMPLE To test a counter component, you would first render it. You'd find the initial count, maybe "Count: 0". Then, you'd use a query like getByRole('button', { name: /increment/i }) to find the increment button. After simulating a click with fireEvent.click, you would assert that the text "Count: 1" is now visible in the document. This test passes regardless of how the state is managed internally, making it robust to refactoring.
Read the original → testing-library.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.