mirror of
https://github.com/sanjeed5/awesome-cursor-rules-mdc.git
synced 2026-11-30 23:04:59 +08:00
Regenerate all MDC rules with fresh Exa data and December 2025 best practices
- Refreshed all 241 library rules with current best practices - Updated Exa search results for all libraries with 2025 content - Fixed --regenerate-all flag logic to properly process all libraries - Removed duplicate astro entry in rules.json (merged tags) - Added missing docker.mdc and vim.mdc files - All rules now include modern patterns and anti-patterns - Updated with framework-specific recommendations for 2025 Technical improvements: - Fixed retry_failed_only logic in generate_mdc_files.py - Improved progress tracking for regeneration scenarios - Ensured proper handling of --refresh-exa flag
This commit is contained in:
+374
-141
@@ -1,157 +1,390 @@
|
||||
---
|
||||
description: Comprehensive Svelte best practices covering code structure, performance, security, testing, and common pitfalls. This rule provides guidance on writing maintainable, efficient, and secure Svelte applications.
|
||||
globs: *.svelte
|
||||
description: Definitive guide for writing clean, performant, and maintainable Svelte 5 applications using the runes API and modern TypeScript practices.
|
||||
globs: **/*.{svelte,js,ts}
|
||||
---
|
||||
- **Manipulate the DOM with HTML:** Utilize Svelte's HTML-centric approach to manipulate the DOM.
|
||||
- **Solve challenges with HTML/CSS first:** Prioritize solving problems with HTML and CSS before resorting to JavaScript.
|
||||
- **Write short components:** Aim for concise and focused components to improve readability and maintainability.
|
||||
- **Write concise reactive `$:` blocks:** Keep reactive statements short and easy to understand.
|
||||
- **Scope CSS to the actual component:** Ensure that CSS styles are scoped to the component to avoid conflicts.
|
||||
- **Avoid hard coding data or dimensions:** Use dynamic data and responsive design techniques instead of hard-coded values.
|
||||
- **Keep objects immutable:** Treat objects as immutable to prevent unexpected side effects and improve performance.
|
||||
- **Use two-way binding effectively:** Leverage two-way binding for efficient data synchronization but be mindful of its potential impact on performance for complex scenarios.
|
||||
# Svelte Best Practices (Svelte 5 + TypeScript)
|
||||
|
||||
## 1. Code Organization and Structure:
|
||||
This guide outlines the definitive best practices for developing Svelte 5 applications with TypeScript. We prioritize explicit reactivity, strong typing, and compiler-driven performance.
|
||||
|
||||
- **Directory Structure Best Practices:**
|
||||
- `src/`: Contains all the application source code.
|
||||
- `src/components/`: Holds reusable Svelte components, categorized further by feature or domain (e.g., `src/components/Button/`, `src/components/Form/`).
|
||||
- `src/lib/`: Contains utility functions, helper modules, and reusable logic that is not specific to a component.
|
||||
- `src/routes/`: For SvelteKit applications, this directory defines the application's routes.
|
||||
- `src/stores/`: Stores for global state management (if using Svelte's stores).
|
||||
- `static/`: Static assets like images, fonts, and other resources.
|
||||
- **File Naming Conventions:**
|
||||
- Components: Use PascalCase (e.g., `MyComponent.svelte`).
|
||||
- Utility functions: Use camelCase (e.g., `formatDate.js`).
|
||||
- Stores: Use descriptive names related to the data they hold (e.g., `userStore.js`).
|
||||
- **Module Organization:**
|
||||
- Group related components and utilities into modules within their respective directories.
|
||||
- Use `index.js` or `index.svelte` files to export multiple components or functions from a directory, providing a cleaner import experience.
|
||||
- **Component Architecture:**
|
||||
- Favor a component-based architecture where UI is broken down into small, reusable components.
|
||||
- Consider using a composition pattern where complex components are built by composing simpler ones.
|
||||
- Separate concerns: Keep components focused on presentation logic and delegate data fetching or business logic to services or stores.
|
||||
- **Code Splitting Strategies:**
|
||||
- Use dynamic imports (`import()`) to load components or modules on demand, reducing the initial bundle size.
|
||||
- Leverage SvelteKit's built-in code splitting capabilities for route-based splitting.
|
||||
- Consider splitting large components into smaller, lazily loaded sub-components.
|
||||
## 1. Code Organization and Structure
|
||||
|
||||
## 2. Common Patterns and Anti-patterns:
|
||||
Always structure your Svelte components for clarity and maintainability.
|
||||
|
||||
- **Design Patterns Specific to Svelte:**
|
||||
- **Store pattern:** Use Svelte's stores for managing application state and reactivity.
|
||||
- **Action pattern:** Use Svelte's actions for manipulating DOM elements or integrating with third-party libraries.
|
||||
- **Component composition:** Build complex UIs by composing smaller, reusable components.
|
||||
- **Recommended Approaches for Common Tasks:**
|
||||
- **Form handling:** Use Svelte's two-way binding (`bind:value`) for simple forms. For more complex scenarios, consider libraries like Formik or Svelte Formly.
|
||||
- **Data fetching:** Use `fetch` or libraries like Axios for fetching data from APIs. Handle loading and error states appropriately.
|
||||
- **Event handling:** Use Svelte's event directives (e.g., `on:click`) for handling DOM events.
|
||||
- **Anti-patterns and Code Smells to Avoid:**
|
||||
- **Overusing global state:** Avoid putting everything in a global store. Use component-level state when appropriate.
|
||||
- **Directly manipulating the DOM outside of actions:** Rely on Svelte's reactivity system to update the DOM.
|
||||
- **Writing overly complex components:** Break down large components into smaller, more manageable ones.
|
||||
- **State Management Best Practices:**
|
||||
- Use Svelte's built-in stores for managing global or application-level state.
|
||||
- Consider using reactive declarations (`$:`) to derive state from other state variables.
|
||||
- Keep state updates predictable and avoid modifying state directly.
|
||||
- For complex state management needs, explore libraries like Redux or Zustand (though often unnecessary in Svelte).
|
||||
- **Error Handling Patterns:**
|
||||
- Use try-catch blocks to handle potential errors during data fetching or other asynchronous operations.
|
||||
- Display user-friendly error messages in the UI.
|
||||
- Log errors to the console or a logging service for debugging purposes.
|
||||
- Implement global error handling to catch unhandled exceptions.
|
||||
### 1.1. HTML-First Component Design
|
||||
|
||||
## 3. Performance Considerations:
|
||||
Keep your component logic, markup, and styles co-located within the `.svelte` file. This is Svelte's core philosophy.
|
||||
|
||||
- **Optimization Techniques:**
|
||||
- **Minimize DOM updates:** Svelte is very efficient at updating the DOM, but unnecessary updates can still impact performance. Use reactive declarations judiciously.
|
||||
- **Use `{#each}` blocks efficiently:** Key your `{#each}` blocks with unique identifiers to help Svelte efficiently update the list.
|
||||
- **Avoid unnecessary component re-renders:** Use the `$:` syntax effectively to only update components when necessary.
|
||||
- **Memory Management:**
|
||||
- Avoid memory leaks by properly cleaning up event listeners and subscriptions when components are destroyed (using `onDestroy`).
|
||||
- Be mindful of large data structures in stores, and consider using techniques like pagination or virtualization to manage them efficiently.
|
||||
- **Rendering Optimization:**
|
||||
- Use the `svelte:options` tag with the `immutable` option for components that receive immutable data as props.
|
||||
- Use `shouldUpdate` to prevent rendering for unchanged immutable props.
|
||||
- **Bundle Size Optimization:**
|
||||
- Use production builds with minification and tree shaking to remove unused code.
|
||||
- Use dynamic imports for code splitting.
|
||||
- Optimize images and other assets.
|
||||
- **Lazy Loading Strategies:**
|
||||
- Use dynamic imports to lazy load components or modules that are not immediately needed.
|
||||
- Implement lazy loading for images or other resources that are below the fold.
|
||||
**❌ BAD: Over-abstracting into separate JS files for simple logic**
|
||||
```svelte
|
||||
<!-- MyComponent.svelte -->
|
||||
<script lang="ts">
|
||||
import { calculateValue } from './utils'; // Unnecessary abstraction
|
||||
let count = $state(0);
|
||||
let computed = $derived(calculateValue(count));
|
||||
</script>
|
||||
```
|
||||
|
||||
## 4. Security Best Practices:
|
||||
**✅ GOOD: Keep related logic within the component**
|
||||
```svelte
|
||||
<!-- MyComponent.svelte -->
|
||||
<script lang="ts">
|
||||
let count = $state(0);
|
||||
let computed = $derived(count * 2 + 1); // Simple logic stays here
|
||||
</script>
|
||||
```
|
||||
|
||||
- **Common Vulnerabilities and How to Prevent Them:**
|
||||
- **Cross-Site Scripting (XSS):** Sanitize user input before displaying it in the UI. Svelte automatically escapes HTML entities, but be careful when using `@html` or `{@debug}`.
|
||||
- **Cross-Site Request Forgery (CSRF):** Use CSRF tokens to protect against CSRF attacks.
|
||||
- **SQL Injection:** If interacting with a database, use parameterized queries to prevent SQL injection attacks.
|
||||
- **Input Validation:**
|
||||
- Validate user input on both the client-side and server-side.
|
||||
- Use appropriate data types and validation rules to prevent invalid data from being processed.
|
||||
- **Authentication and Authorization Patterns:**
|
||||
- Use secure authentication mechanisms like OAuth or JWT.
|
||||
- Implement proper authorization checks to ensure that users only have access to the resources they are allowed to access.
|
||||
- **Data Protection Strategies:**
|
||||
- Encrypt sensitive data at rest and in transit.
|
||||
- Use secure storage mechanisms for storing sensitive data.
|
||||
- **Secure API Communication:**
|
||||
- Use HTTPS for all API communication.
|
||||
- Validate API responses to ensure that they are valid and not malicious.
|
||||
### 1.2. TypeScript Everywhere
|
||||
|
||||
## 5. Testing Approaches:
|
||||
Use `lang="ts"` in all `<script>` tags. Configure `svelte-check` in CI and use the VS Code extension for real-time feedback.
|
||||
|
||||
- **Unit Testing Strategies:**
|
||||
- Use a testing framework like Jest or Mocha to write unit tests for individual components and utility functions.
|
||||
- Mock external dependencies to isolate the code being tested.
|
||||
- **Integration Testing:**
|
||||
- Use a testing framework like Cypress or Playwright to write integration tests that verify the interaction between different components or modules.
|
||||
- Test the integration with APIs and other external services.
|
||||
- **End-to-End Testing:**
|
||||
- Use a testing framework like Cypress or Playwright to write end-to-end tests that simulate user interactions with the application.
|
||||
- Test the entire application flow from start to finish.
|
||||
- **Test Organization:**
|
||||
- Organize tests into directories that mirror the application's directory structure.
|
||||
- Use descriptive names for test files and test cases.
|
||||
- **Mocking and Stubbing:**
|
||||
- Use mocking libraries like Jest's `jest.fn()` or Sinon.js to mock external dependencies.
|
||||
- Use stubbing to replace complex or slow dependencies with simpler implementations for testing purposes.
|
||||
**❌ BAD: Missing `lang="ts"`**
|
||||
```svelte
|
||||
<script>
|
||||
let name: string = 'world'; // No type checking
|
||||
</script>
|
||||
```
|
||||
|
||||
## 6. Common Pitfalls and Gotchas:
|
||||
**✅ GOOD: Explicitly enable TypeScript**
|
||||
```svelte
|
||||
<script lang="ts">
|
||||
let name: string = 'world'; // Full type safety
|
||||
</script>
|
||||
```
|
||||
|
||||
- **Frequent Mistakes Developers Make:**
|
||||
- **Incorrect reactivity usage:** Failing to understand how Svelte's reactivity system works can lead to unexpected behavior.
|
||||
- **Over-reliance on `$: `:** Although reactive declarations are powerful, overusing them can make code harder to read and debug. Consider if a regular variable or function would be more appropriate.
|
||||
- **Mutating props directly:** Modifying props directly inside a component can lead to unexpected side effects.
|
||||
- **Edge Cases to Be Aware Of:**
|
||||
- **Transition and animation behavior:** Understanding how transitions and animations interact with component updates is important for creating smooth user experiences.
|
||||
- **Server-side rendering (SSR) considerations:** When using SvelteKit, be aware of the differences between client-side and server-side execution environments.
|
||||
- **Version-Specific Issues:**
|
||||
- Consult the Svelte changelog and migration guides when upgrading to a new version to avoid compatibility issues.
|
||||
- **Compatibility Concerns:**
|
||||
- Ensure that your code is compatible with the target browsers and devices.
|
||||
- Use polyfills or transpilers to support older browsers if necessary.
|
||||
- **Debugging Strategies:**
|
||||
- Use the Svelte Devtools browser extension for inspecting component state and reactivity.
|
||||
- Use `console.log` or the `debugger` statement to debug code execution.
|
||||
- Use SvelteKit's built-in error handling and logging features.
|
||||
## 2. Component Architecture (Svelte 5 Runes)
|
||||
|
||||
## 7. Tooling and Environment:
|
||||
Svelte 5's runes API makes reactivity explicit and powerful. Embrace it fully.
|
||||
|
||||
- **Recommended Development Tools:**
|
||||
- **VS Code with the Svelte extension:** Provides syntax highlighting, code completion, and other useful features.
|
||||
- **Svelte Devtools:** A browser extension for inspecting Svelte component state and reactivity.
|
||||
- **ESLint and Prettier:** For linting and formatting code.
|
||||
- **Build Configuration:**
|
||||
- Use a build tool like Vite or Rollup to bundle your Svelte code for production.
|
||||
- Configure the build tool to perform optimizations like minification and tree shaking.
|
||||
- **Linting and Formatting:**
|
||||
- Use ESLint with the `eslint-plugin-svelte3` plugin to lint your Svelte code.
|
||||
- Use Prettier with the `prettier-plugin-svelte` plugin to format your Svelte code.
|
||||
- **Deployment Best Practices:**
|
||||
- Deploy your Svelte application to a CDN or a serverless platform like Netlify or Vercel.
|
||||
- Configure your server to serve the application's static assets with proper caching headers.
|
||||
- **CI/CD Integration:**
|
||||
- Use a CI/CD platform like GitHub Actions or GitLab CI to automate the build, testing, and deployment process.
|
||||
- Run tests and linting checks on every commit to ensure code quality.
|
||||
### 2.1. Explicit Reactive State with `$state`
|
||||
|
||||
Declare all reactive state using `$state`. This makes your component's reactivity clear and refactor-friendly.
|
||||
|
||||
**❌ BAD: Implicit reactivity (Svelte 4 style)**
|
||||
```svelte
|
||||
<script lang="ts">
|
||||
let count = 0; // Not reactive outside top-level
|
||||
function increment() { count++; }
|
||||
</script>
|
||||
```
|
||||
|
||||
**✅ GOOD: Explicit `$state` for all reactive variables**
|
||||
```svelte
|
||||
<script lang="ts">
|
||||
let count = $state(0); // Clearly reactive
|
||||
function increment() { count++; }
|
||||
</script>
|
||||
```
|
||||
|
||||
### 2.2. Derived State with `$derived`
|
||||
|
||||
Use `$derived` for any value that is a pure computation of other reactive state.
|
||||
|
||||
**❌ BAD: `$effect` or `$:` for derived values**
|
||||
```svelte
|
||||
<script lang="ts">
|
||||
let count = $state(0);
|
||||
$effect(() => { // Incorrectly using effect for derivation
|
||||
console.log('Count changed:', count);
|
||||
// This is a side effect, not a derivation
|
||||
});
|
||||
$: doubled = count * 2; // Svelte 4 style, less explicit
|
||||
</script>
|
||||
```
|
||||
|
||||
**✅ GOOD: `$derived` for pure computations**
|
||||
```svelte
|
||||
<script lang="ts">
|
||||
let count = $state(0);
|
||||
let doubled = $derived(count * 2); // Clearly a derived value
|
||||
</script>
|
||||
```
|
||||
|
||||
### 2.3. Side Effects with `$effect`
|
||||
|
||||
Reserve `$effect` for actual side effects (e.g., DOM manipulation, API calls, logging).
|
||||
|
||||
**❌ BAD: Mixing derivations and effects**
|
||||
```svelte
|
||||
<script lang="ts">
|
||||
let count = $state(0);
|
||||
$: if (count > 5) { // Svelte 4 style, combines derivation and effect
|
||||
alert('Count is too high!');
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
**✅ GOOD: Clear separation of concerns**
|
||||
```svelte
|
||||
<script lang="ts">
|
||||
let count = $state(0);
|
||||
$effect(() => { // Clearly a side effect
|
||||
if (count > 5) {
|
||||
alert('Count is too high!');
|
||||
}
|
||||
});
|
||||
</script>
|
||||
```
|
||||
|
||||
### 2.4. Component Properties with `$props`
|
||||
|
||||
Declare all component properties using the `$props()` rune and destructuring. This provides powerful type safety and flexibility.
|
||||
|
||||
**❌ BAD: `export let` (Svelte 4 style)**
|
||||
```svelte
|
||||
<script lang="ts">
|
||||
export let name: string;
|
||||
export let age: number = 30;
|
||||
</script>
|
||||
```
|
||||
|
||||
**✅ GOOD: `$props()` for properties**
|
||||
```svelte
|
||||
<script lang="ts">
|
||||
interface Props {
|
||||
name: string;
|
||||
age?: number; // Optional prop
|
||||
}
|
||||
let { name, age = 30 }: Props = $props();
|
||||
</script>
|
||||
```
|
||||
|
||||
### 2.5. Event Handling
|
||||
|
||||
Remove the `on:` prefix for event handlers. They are now standard properties.
|
||||
|
||||
**❌ BAD: `on:click`**
|
||||
```svelte
|
||||
<button on:click={() => alert('Clicked!')}>Click me</button>
|
||||
```
|
||||
|
||||
**✅ GOOD: `onclick` (standard HTML attribute)**
|
||||
```svelte
|
||||
<button onclick={() => alert('Clicked!')}>Click me</button>
|
||||
```
|
||||
|
||||
### 2.6. Slots and Snippets
|
||||
|
||||
Use `{@render}` for rendering slots and snippets, providing type safety and better control over content.
|
||||
|
||||
**❌ BAD: Untyped slots**
|
||||
```svelte
|
||||
<!-- MyComponent.svelte -->
|
||||
<slot />
|
||||
```
|
||||
|
||||
**✅ GOOD: Typed snippets for predictable content**
|
||||
```svelte
|
||||
<!-- MyComponent.svelte -->
|
||||
<script lang="ts">
|
||||
import type { Snippet } from 'svelte';
|
||||
let { header }: { header: Snippet } = $props();
|
||||
</script>
|
||||
<div>
|
||||
{@render header()}
|
||||
<slot />
|
||||
</div>
|
||||
```
|
||||
|
||||
## 3. State Management
|
||||
|
||||
Prioritize local component state with `$state`. Use Svelte stores for truly global or complex cross-component state.
|
||||
|
||||
### 3.1. Local State First
|
||||
|
||||
Most state should live within the component using `$state`.
|
||||
|
||||
**❌ BAD: Over-reliance on global stores for simple component state**
|
||||
```svelte
|
||||
// store.ts
|
||||
import { writable } from 'svelte/store';
|
||||
export const localCounter = writable(0); // Unnecessary global
|
||||
```
|
||||
|
||||
**✅ GOOD: Use `$state` for component-local reactivity**
|
||||
```svelte
|
||||
<script lang="ts">
|
||||
let count = $state(0); // Local to this component
|
||||
</script>
|
||||
```
|
||||
|
||||
### 3.2. Svelte Stores for Global State
|
||||
|
||||
For state shared across many components or complex application-wide state, use Svelte's built-in stores.
|
||||
|
||||
```ts
|
||||
// src/lib/stores/auth.ts
|
||||
import { writable } from 'svelte/store';
|
||||
export const isAuthenticated = writable(false);
|
||||
export const user = writable<{ id: string; name: string } | null>(null);
|
||||
```
|
||||
```svelte
|
||||
<!-- AuthStatus.svelte -->
|
||||
<script lang="ts">
|
||||
import { isAuthenticated, user } from '$lib/stores/auth';
|
||||
</script>
|
||||
{#if $isAuthenticated}
|
||||
<p>Welcome, {$user?.name}!</p>
|
||||
{:else}
|
||||
<p>Please log in.</p>
|
||||
{/if}
|
||||
```
|
||||
|
||||
## 4. Performance Considerations
|
||||
|
||||
SvelteKit handles many optimizations automatically. Supplement these with mindful coding.
|
||||
|
||||
### 4.1. `{#each}` with Keys
|
||||
|
||||
Always provide a unique `key` to `{#each}` blocks for efficient DOM updates.
|
||||
|
||||
**❌ BAD: Missing `key`**
|
||||
```svelte
|
||||
{#each items as item}
|
||||
<ItemComponent {item} />
|
||||
{/each}
|
||||
```
|
||||
|
||||
**✅ GOOD: Use a unique `key`**
|
||||
```svelte
|
||||
{#each items as item (item.id)}
|
||||
<ItemComponent {item} />
|
||||
{/each}
|
||||
```
|
||||
|
||||
### 4.2. Dynamic Imports for Lazy Loading
|
||||
|
||||
Lazy-load components or modules that aren't immediately needed to reduce initial bundle size.
|
||||
|
||||
```svelte
|
||||
<script lang="ts">
|
||||
let showModal = $state(false);
|
||||
async function openModal() {
|
||||
const { default: Modal } = await import('./Modal.svelte');
|
||||
// Render Modal component
|
||||
showModal = true;
|
||||
}
|
||||
</script>
|
||||
{#if showModal}
|
||||
<Modal />
|
||||
{/if}
|
||||
<button onclick={openModal}>Open Modal</button>
|
||||
```
|
||||
|
||||
## 5. Common Pitfalls and Gotchas
|
||||
|
||||
Avoid these common mistakes to ensure robust and predictable Svelte applications.
|
||||
|
||||
### 5.1. Misunderstanding `$effect` Dependencies
|
||||
|
||||
`$effect` runs when its *dependencies* change. Be explicit about what it depends on.
|
||||
|
||||
**❌ BAD: Implicit dependencies or missing cleanup**
|
||||
```svelte
|
||||
<script lang="ts">
|
||||
let count = $state(0);
|
||||
$effect(() => {
|
||||
// This effect might not re-run if `count` isn't directly used
|
||||
// or if `doSomething` has internal state changes not tracked by Svelte.
|
||||
doSomething(count);
|
||||
});
|
||||
</script>
|
||||
```
|
||||
|
||||
**✅ GOOD: Explicit dependencies and cleanup**
|
||||
```svelte
|
||||
<script lang="ts">
|
||||
let count = $state(0);
|
||||
$effect(() => {
|
||||
const timer = setInterval(() => {
|
||||
console.log('Count is', count); // `count` is a dependency
|
||||
}, 1000);
|
||||
return () => clearInterval(timer); // Cleanup function
|
||||
});
|
||||
</script>
|
||||
```
|
||||
|
||||
### 5.2. Forgetting `generics` Attribute
|
||||
|
||||
When creating generic components, remember to add the `generics` attribute to the `<script>` tag.
|
||||
|
||||
**❌ BAD: Untyped generic props**
|
||||
```svelte
|
||||
<script lang="ts">
|
||||
interface Props { items: any[]; } // Loses type safety
|
||||
let { items }: Props = $props();
|
||||
</script>
|
||||
```
|
||||
|
||||
**✅ GOOD: Explicit generics for type safety**
|
||||
```svelte
|
||||
<script lang="ts" generics="Item extends { id: string }">
|
||||
interface Props { items: Item[]; }
|
||||
let { items }: Props = $props();
|
||||
</script>
|
||||
```
|
||||
|
||||
## 6. Accessibility
|
||||
|
||||
Build accessible Svelte applications by default.
|
||||
|
||||
### 6.1. Semantic HTML
|
||||
|
||||
Always prefer semantic HTML elements over generic `div`s or `span`s.
|
||||
|
||||
**❌ BAD: Non-semantic button**
|
||||
```svelte
|
||||
<div onclick={handleClick} role="button" tabindex="0">Click me</div>
|
||||
```
|
||||
|
||||
**✅ GOOD: Semantic HTML element**
|
||||
```svelte
|
||||
<button onclick={handleClick}>Click me</button>
|
||||
```
|
||||
|
||||
### 6.2. ARIA Attributes
|
||||
|
||||
Use ARIA attributes when semantic HTML isn't sufficient, but only when necessary.
|
||||
|
||||
```svelte
|
||||
<label for="username">Username</label>
|
||||
<input id="username" type="text" aria-describedby="username-hint" />
|
||||
<p id="username-hint">Your username must be unique.</p>
|
||||
```
|
||||
|
||||
## 7. Testing Approaches
|
||||
|
||||
Implement a robust testing strategy for Svelte applications.
|
||||
|
||||
### 7.1. Unit Testing with Vitest and Svelte Testing Library
|
||||
|
||||
Use `vitest` for your test runner and `@testing-library/svelte` for component testing.
|
||||
|
||||
```ts
|
||||
// src/lib/components/Counter.test.ts
|
||||
import { render, screen } from '@testing-library/svelte';
|
||||
import { expect, test } from 'vitest';
|
||||
import Counter from './Counter.svelte';
|
||||
|
||||
test('Counter increments value on click', async () => {
|
||||
render(Counter);
|
||||
const button = screen.getByRole('button', { name: /Count:/i });
|
||||
expect(button).toHaveTextContent('Count: 0');
|
||||
await button.click();
|
||||
expect(button).toHaveTextContent('Count: 1');
|
||||
});
|
||||
```
|
||||
|
||||
### 7.2. End-to-End (E2E) Testing
|
||||
|
||||
For critical user flows, use `Playwright` or `Cypress`.
|
||||
|
||||
```ts
|
||||
// tests/example.spec.ts (Playwright)
|
||||
import { test, expect } from '@playwright/test';
|
||||
|
||||
test('homepage has title and intro text', async ({ page }) => {
|
||||
await page.goto('/');
|
||||
await expect(page).toHaveTitle(/SvelteKit/);
|
||||
await expect(page.locator('h1')).toHaveText('Welcome to SvelteKit');
|
||||
});
|
||||
```
|
||||
Reference in New Issue
Block a user