### Install SvelteKit Embed
Source: https://github.com/spences10/sveltekit-embed/blob/main/README.md
Installs the sveltekit-embed package as a development dependency using npm.
```bash
npm i -D sveltekit-embed
```
--------------------------------
### Install sveltekit-embed
Source: https://github.com/spences10/sveltekit-embed/blob/main/packages/sveltekit-embed/README.md
Installs the sveltekit-embed package using npm, pnpm, or yarn.
```bash
npm install sveltekit-embed
```
```bash
pnpm add sveltekit-embed
```
```bash
yarn add sveltekit-embed
```
--------------------------------
### Embed CodePen Examples in SvelteKit
Source: https://github.com/spences10/sveltekit-embed/blob/main/packages/sveltekit-embed/README.md
Demonstrates embedding CodePen examples using the CodePen component from sveltekit-embed. Allows setting the `codePenId`, `height`, `defaultTab`, and `theme`.
```svelte
```
--------------------------------
### Alternative CI Configurations for Playwright
Source: https://github.com/spences10/sveltekit-embed/blob/main/packages/sveltekit-embed/TESTING_STRATEGY.md
Provides example CI/CD configurations for GitLab CI and CircleCI that utilize the Playwright Docker container for running tests. These examples demonstrate how to adapt the container strategy for different CI platforms.
```yaml
# GitLab CI
test:
image: mcr.microsoft.com/playwright:v1.52.0-noble
script:
- npm ci
- npm run test:ci
# CircleCI
jobs:
test:
docker:
- image: mcr.microsoft.com/playwright:v1.52.0-noble
steps:
- checkout
- run: npm ci
- run: npm run test:ci
```
--------------------------------
### Vitest Browser Setup for Svelte Components
Source: https://github.com/spences10/sveltekit-embed/blob/main/packages/sveltekit-embed/TESTING_STRATEGY.md
Minimal setup file for Vitest browser environment in SvelteKit, leveraging real browser APIs and Playwright matchers. No complex mocking is needed due to direct DOM API usage.
```typescript
///
///
```
--------------------------------
### Install sveltekit-embed
Source: https://github.com/spences10/sveltekit-embed/blob/main/apps/web/src/routes/+page.md
Installs the sveltekit-embed package as a development dependency using pnpm. This command can also be used with npm or yarn.
```bash
pnpm i -D sveltekit-embed # npm or yarn even
```
--------------------------------
### Use YouTube, Spotify, and CodePen Embeds in SvelteKit
Source: https://github.com/spences10/sveltekit-embed/blob/main/packages/sveltekit-embed/README.md
Demonstrates how to import and use YouTube, Spotify, and CodePen embed components within a SvelteKit application. Includes examples of setting component-specific props.
```svelte
```
--------------------------------
### TypeScript: Correct Mock Setup Before Imports
Source: https://github.com/spences10/sveltekit-embed/blob/main/packages/sveltekit-embed/TESTING_STRATEGY.md
This snippet illustrates the proper method for setting up mocks in tests, emphasizing that mocks must be declared before the module they are mocking is imported to ensure they are applied correctly.
```typescript
// ❌ Mock after import
import { myFunction } from './module';
vi.mock('./module');
// ✅ Mock before import
vi.mock('./module', () => ({
myFunction: vi.fn(),
}));
import { myFunction } from './module';
```
--------------------------------
### Embed Spotify Content in SvelteKit
Source: https://github.com/spences10/sveltekit-embed/blob/main/packages/sveltekit-embed/README.md
Provides examples for embedding Spotify tracks, albums, and playlists using the Spotify component from sveltekit-embed. The `spotifyLink` prop is used to specify the content.
```svelte
```
--------------------------------
### Test User Behavior vs. Implementation Details (TypeScript)
Source: https://github.com/spences10/sveltekit-embed/blob/main/packages/sveltekit-embed/TESTING_STRATEGY.md
Illustrates the difference between testing implementation details (which can lead to brittle tests) and testing user-observable behavior. The example shows how to assert the outcome of a user interaction.
```typescript
// ❌ Testing implementation details
test('calls internal method', () => {
const component = render(MyComponent);
expect(component.internalMethod).toHaveBeenCalled();
});
// ✅ Testing user behavior
test('shows success message after form submission', async () => {
const { container } = render(ContactForm);
await container.querySelector('[data-testid="submit"]').click();
expect(container.textContent?.includes('Success!')).toBe(true);
});
```
--------------------------------
### GitHub Actions CI Configuration with Playwright Container
Source: https://github.com/spences10/sveltekit-embed/blob/main/packages/sveltekit-embed/TESTING_STRATEGY.md
Configures a GitHub Actions workflow to run unit tests using the official Playwright Docker container. This setup optimizes CI performance by leveraging pre-installed browsers and a consistent testing environment.
```yaml
# .github/workflows/unit-test.yml
jobs:
unit-tests:
name: Run unit tests
runs-on: ubuntu-latest
container:
image: mcr.microsoft.com/playwright:v1.52.0-noble
options: --user 1001
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4.1.0
- uses: actions/setup-node@v4
with:
node-version: 22.x
cache: 'pnpm'
- name: Install dependencies
run: pnpm install
- name: Test
run: pnpm run test:ci
```
--------------------------------
### TypeScript: Alternatives for Locator Chaining
Source: https://github.com/spences10/sveltekit-embed/blob/main/packages/sveltekit-embed/TESTING_STRATEGY.md
This example addresses the lack of `.locator()` chaining support in vitest-browser-svelte. It offers alternative strategies for finding nested elements, such as using global semantic queries, more specific selectors, or test IDs.
```typescript
// ❌ Chaining locators (not supported in vitest-browser-svelte)
const banner = page.getByRole('banner');
const link = banner.locator('a'); // Error: Property 'locator' does not exist
// ✅ Use semantic queries from page object
const banner = page.getByRole('banner');
const link = page.getByRole('link'); // Find link anywhere on page
// ✅ Use more specific selectors
const link = page.getByRole('link', { name: 'specific link text' });
// ✅ Use test IDs for complex nested structures
const link = page.getByTestId('banner-link');
```
--------------------------------
### Test Svelte 5 Classes with Vitest
Source: https://github.com/spences10/sveltekit-embed/blob/main/packages/sveltekit-embed/TESTING_STRATEGY.md
This example shows how to test Svelte 5 classes defined in `.svelte.ts` files using Vitest. It includes the class definition and corresponding tests to verify its functionality, including reactivity.
```typescript
// doubler.svelte.ts
export class Doubler {
#getNumber;
#double = $derived(this.#getNumber() * 2);
constructor(getNumber: () => number) {
this.#getNumber = getNumber;
}
get value() {
return this.#double;
}
}
// doubler.svelte.test.ts
import { describe, expect, it } from 'vitest';
import { Doubler } from './doubler.svelte.ts';
describe('doubler.svelte.ts', () => {
it('should double initial value', () => {
let value = $state(1);
let doubler = new Doubler(() => value);
expect(doubler.value).toBe(2);
});
it('should be reactive', () => {
let value = $state(0);
let doubler = new Doubler(() => value);
expect(doubler.value).toBe(0);
value = 2;
expect(doubler.value).toBe(4);
});
});
```
--------------------------------
### Test HTML Output for SSR in Vitest
Source: https://github.com/spences10/sveltekit-embed/blob/main/packages/sveltekit-embed/TESTING_STRATEGY.md
This example focuses on testing the generated HTML output for Server-Side Rendering (SSR) in Vitest. It shows how to assert the presence of specific content within the rendered HTML body, including dynamic data.
```typescript
test('generates correct HTML structure', () => {
const { body } = render(ProductCard, {
props: {
title: 'Test Product',
price: 29.99,
inStock: true,
},
});
expect(body).toContain('
Test Product
');
expect(body).toContain('$29.99');
expect(body).toContain('In Stock');
expect(body).not.toContain('Out of Stock');
});
```
--------------------------------
### Test Form Input Validation (TypeScript)
Source: https://github.com/spences10/sveltekit-embed/blob/main/packages/sveltekit-embed/TESTING_STRATEGY.md
Provides a practical example of testing form validation in a SvelteKit application. It demonstrates filling an input field, submitting the form, and asserting that an error message is displayed.
```typescript
import { render } from '@testing-library/svelte';
test('validates form input', async () => {
render(ContactForm);
const emailInput = page.getByLabel('Email address');
const submitButton = page.getByRole('button', { name: 'Submit' });
// Test invalid email
await emailInput.fill('invalid-email');
await submitButton.click();
flushSync();
const errorMessage = page.getByText('Invalid email');
await expect.element(errorMessage).toBeInTheDocument();
});
```
--------------------------------
### Add Custom Component to SvelteKit Embed
Source: https://github.com/spences10/sveltekit-embed/blob/main/README.md
Guides on how to create a new Svelte component, export it from the library, and import it into a SvelteKit route for testing and usage.
```typescript
export { default as MyComponent } from './components/my-component.svelte';
```
--------------------------------
### Embed StackBlitz with SvelteKit
Source: https://github.com/spences10/sveltekit-embed/blob/main/apps/web/src/routes/+page.md
Allows embedding StackBlitz projects with options for dimensions, view mode, theme, file display, and navigation visibility. The component uses TypeScript for props and HTML for usage examples.
```typescript
width: string = '100%'
height: string = '500px'
id: string = ''
view: 'editor' | 'preview' | 'default' = 'default'
clickToLoad: boolean = true //ctl
hideNavigation: boolean = false //hideNavigation
hideExplorer: boolean = true
theme: string | 'light' | 'dark' | 'default' = 'dark'
file: string | undefined
disable_observer: boolean = false
iframe_styles: string = `
height: ${height};
width: ${width};
`
```
```html
```
--------------------------------
### TypeScript: Handle Async Test Issues with vi.waitFor
Source: https://github.com/spences10/sveltekit-embed/blob/main/packages/sveltekit-embed/TESTING_STRATEGY.md
This example shows how to resolve timing issues in asynchronous tests by utilizing `vi.waitFor()`, ensuring that assertions are made only after the expected asynchronous operations have completed.
```typescript
await vi.waitFor(() => {
expect(container.textContent?.includes('Expected text')).toBe(true);
});
```
--------------------------------
### Use flushSync for Derived State in Vitest
Source: https://github.com/spences10/sveltekit-embed/blob/main/packages/sveltekit-embed/TESTING_STRATEGY.md
This example shows when `flushSync()` is necessary in Vitest tests, particularly for testing derived state that requires immediate evaluation. It contrasts this with tests that don't need `flushSync` when using locators for DOM updates.
```typescript
// ✅ Still need flushSync for testing derived state directly
test('derived state logic', async () => {
let scrollState = $state({ current: 0, previous: 0 });
let shouldShow = $derived(
scrollState.current > scrollState.previous,
);
expect(untrack(() => shouldShow)).toBe(false);
scrollState.current = 100;
flushSync(); // Needed for immediate derived state evaluation
expect(untrack(() => shouldShow)).toBe(true);
});
// ✅ No flushSync needed when testing DOM updates with locators
test('component updates DOM', async () => {
render(MyComponent);
const button = page.getByRole('button');
await button.click();
// Locators automatically wait for DOM updates
await expect.element(page.getByText('Updated')).toBeInTheDocument();
});
```
--------------------------------
### Render Svelte Components with Default Props (TypeScript)
Source: https://github.com/spences10/sveltekit-embed/blob/main/packages/sveltekit-embed/TESTING_STRATEGY.md
Provides a reusable test helper function to render Svelte components with common default props, simplifying component testing setup. It utilizes the 'render' function, likely from a testing library.
```typescript
import { render } from '@testing-library/svelte';
// Test helper for rendering components with common props
function renderWithDefaults(Component: any, props = {}) {
return render(Component, {
props: {
// Default props
theme: 'light',
...props,
},
});
}
```
--------------------------------
### Embed YouTube with SvelteKit
Source: https://github.com/spences10/sveltekit-embed/blob/main/apps/web/src/routes/+page.md
This component provides comprehensive embedding of YouTube content, supporting video IDs, playlist IDs, autoplay, looping, mute, branding, and timestamp skipping. Props are defined in TypeScript, with multiple HTML usage examples.
```typescript
youTubeId?: string;
listId?: string;
index?: number = 0;
autoPlay?: boolean = false;
aspectRatio?: string = '16:9';
skipTo?: { h: number; m: number; s: number } = { h: 0, m: 0, s: 0 };
disable_observer?: boolean = false;
iframe_styles?: string = '';
mute?: boolean = false;
controls?: boolean = true;
loop?: boolean = false;
modestBranding?: boolean = false;
rel?: boolean = false;
```
```html
Usage with video ID:
Usage with playlist:
Usage with timestamp:
```
--------------------------------
### Embed Vimeo with SvelteKit
Source: https://github.com/spences10/sveltekit-embed/blob/main/apps/web/src/routes/+page.md
Enables embedding Vimeo videos with options for video ID, autoplay, aspect ratio, and skipping to specific timestamps. The component's props are defined in TypeScript, with usage examples provided in HTML.
```typescript
vimeoId: string = ''
autoPlay: boolean = false
aspectRatio: string = '16:9'
skipTo: { h: 0, m: 0, s: 0 }
disable_observer: boolean = false
```
```html
```
--------------------------------
### Move .sample.env to .env for Development
Source: https://github.com/spences10/sveltekit-embed/blob/main/README.md
Copies the sample environment file to .env, which is required for running the web page and testing new components locally.
```bash
mv .sample.env apps/web/.env
```
--------------------------------
### Publish @next Package to NPM
Source: https://github.com/spences10/sveltekit-embed/blob/main/README.md
Steps to publish a pre-release version of the SvelteKit embed package to npm using the '--tag next' flag.
```bash
# authenticate with npm
npm login
# bump version with npm
npm version 0.0.13
# package with sveltekit
pnpm run package
# publish with tag
npm publish --tag next
# push tags to github
git push --tags
```
--------------------------------
### Publish SvelteKit Embed to NPM
Source: https://github.com/spences10/sveltekit-embed/blob/main/README.md
A sequence of commands to log in to npm, update the package version, package the SvelteKit project, publish to npm, and push tags to GitHub.
```bash
# authenticate with npm
npm login
# bump version with npm
npm version 0.0.8
# package with sveltekit
pnpm run package
# publish
npm publish
# push tags to github
git push --tags
```
--------------------------------
### SvelteKit Testing Commands
Source: https://github.com/spences10/sveltekit-embed/blob/main/packages/sveltekit-embed/TESTING_STRATEGY.md
Lists available pnpm commands for running various types of tests in a SvelteKit project, including all tests, unit tests, client-side tests, SSR tests, server-side tests, and tests in watch or UI modes.
```bash
# Run all tests
pnpm test
# Run only unit tests (both client and server)
pnpm test:unit
# Run only client-side tests (Svelte components)
pnpm test:client
# Run only SSR tests (Server-side rendering)
pnpm test:ssr
# Run only server-side tests (Node.js utilities)
pnpm test:server
# Run tests in watch mode
pnpm test:unit
# Run tests with UI
pnpm test:ui
# Run tests for CI
pnpm test:ci
# Run with coverage
pnpm coverage
# Run E2E tests
pnpm test:e2e
```
--------------------------------
### Running Specific Vitest Tests
Source: https://github.com/spences10/sveltekit-embed/blob/main/packages/sveltekit-embed/TESTING_STRATEGY.md
Demonstrates how to execute specific tests using Vitest, including running a particular test file, filtering tests by a pattern using `--grep`, or running tests within a specific directory.
```bash
# Run specific test file
pnpm vitest src/lib/components/Button.svelte.test.ts
# Run tests matching pattern
pnpm vitest --grep "Button component"
# Run tests in specific directory
pnpm vitest src/lib/utils/
```
--------------------------------
### Embed Tweet with SvelteKit
Source: https://github.com/spences10/sveltekit-embed/blob/main/apps/web/src/routes/+page.md
This component allows embedding tweets, configurable by the tweet link and theme (light or dark). It uses TypeScript for prop definitions and HTML for usage examples.
```typescript
tweetLink: string = '';
theme: string = 'dark' | 'light' = 'light';
```
```html
```
--------------------------------
### Basic Server Test Structure
Source: https://github.com/spences10/sveltekit-embed/blob/main/packages/sveltekit-embed/TESTING_STRATEGY.md
Demonstrates the basic structure for writing server-side tests using Vitest. It includes importing necessary functions, defining a describe block for a specific utility function, and writing a test case to verify its output.
```typescript
import { describe, expect, test } from 'vitest';
import { myUtilFunction } from './utils';
describe('myUtilFunction', () => {
test('returns expected result', () => {
const result = myUtilFunction('input');
expect(result).toBe('expected output');
});
});
```
--------------------------------
### Core Testing Dependencies for SvelteKit
Source: https://github.com/spences10/sveltekit-embed/blob/main/packages/sveltekit-embed/TESTING_STRATEGY.md
Lists the essential npm dependencies required for setting up Vitest and Playwright for SvelteKit testing. Includes Vitest, browser extensions, and Playwright for browser automation.
```json
{
"vitest": "^3.1.4",
"@vitest/browser": "^3.1.4",
"vitest-browser-svelte": "^0.1.0",
"playwright": "^1.52.0",
"@playwright/test": "^1.52.0"
}
```
--------------------------------
### Migrate from Container Queries to Locators
Source: https://github.com/spences10/sveltekit-embed/blob/main/packages/sveltekit-embed/TESTING_STRATEGY.md
Illustrates the migration from older container query-based DOM querying to the modern locator-based approach. It shows a comparison between the old and new methods for finding and asserting on a button element.
```typescript
// ❌ Old approach (container queries)
test('finds button', () => {
const { container } = render(MyComponent);
const button = container.querySelector('[data-testid="submit"]');
expect(button?.textContent).toBe('Submit');
});
// ✅ New approach (locators)
test('finds button', async () => {
render(MyComponent);
const button = page.getByTestId('submit');
await expect.element(button).toHaveTextContent('Submit');
});
```
--------------------------------
### Basic SSR Test Structure in Vitest
Source: https://github.com/spences10/sveltekit-embed/blob/main/packages/sveltekit-embed/TESTING_STRATEGY.md
This snippet provides a basic structure for Server-Side Rendering (SSR) tests in Vitest. It outlines the file naming convention (`.ssr.test.ts`) and demonstrates a simple test case for rendering a component with props.
```typescript
import { describe, expect, test } from 'vitest';
import { render } from 'svelte/server';
import MyComponent from './MyComponent.svelte';
describe('MyComponent SSR', () => {
test('renders with props', () => {
const { body } = render(MyComponent, {
props: { name: 'World' },
});
expect(body).toContain('Hello, World!');
});
});
```
--------------------------------
### TypeScript: Specify Elements with Locator Methods
Source: https://github.com/spences10/sveltekit-embed/blob/main/packages/sveltekit-embed/TESTING_STRATEGY.md
This snippet provides solutions for when locators match multiple elements, leading to errors. It shows how to use `.first()`, `.last()`, or `.nth()` to select a specific element, or alternatively, use more specific selectors.
```typescript
// ❌ Matches multiple elements
const element = page.getByText(/common-word/);
// ✅ Specify which element you want
const element = page.getByText(/common-word/).first();
const element = page.getByText(/common-word/).last();
const element = page.getByText(/common-word/).nth(1);
// ✅ More specific selector
const element = page.getByTestId('specific-element');
const element = page.getByRole('button', { name: 'Specific Button' });
```
--------------------------------
### Locator Methods for DOM Queries
Source: https://github.com/spences10/sveltekit-embed/blob/main/packages/sveltekit-embed/TESTING_STRATEGY.md
Details various locator methods available for querying the DOM in SvelteKit testing. It covers semantic queries like `getByRole` and `getByLabel`, test ID queries, and other useful methods, recommending semantic queries as the preferred approach.
```typescript
// Semantic queries (preferred)
page.getByRole('button'); // Find by ARIA role
page.getByRole('button', { name: 'Submit' }); // Find by role and accessible name
page.getByLabel('Email address'); // Find by associated label
page.getByPlaceholder('Enter your email'); // Find by placeholder text
page.getByText('Welcome'); // Find by text content
// Test ID queries (when semantic queries aren't possible)
page.getByTestId('submit-button'); // Find by data-testid attribute
// Other useful queries
page.getByTitle('Close dialog'); // Find by title attribute
page.getByAltText('Profile picture'); // Find by alt text (images)
```
--------------------------------
### Test Date Formatting with Mocks
Source: https://github.com/spences10/sveltekit-embed/blob/main/packages/sveltekit-embed/TESTING_STRATEGY.md
Shows how to test a function that depends on external libraries, specifically 'date-fns', by mocking the dependency. It uses `vi.mock` to mock the 'date-fns' module and `vi.mocked` to mock a specific function, then asserts the correct formatting of a date.
```typescript
import { describe, expect, test, vi } from 'vitest';
import { formatDistanceStrict } from 'date-fns';
// Mock external dependencies
vi.mock('date-fns', () => ({
formatDistanceStrict: vi.fn(),
}));
test('formats date correctly', () => {
const mockDate = '2023-01-01';
const mockResult = '2 months ago';
vi.mocked(formatDistanceStrict).mockReturnValue(mockResult);
const result = formatDate(mockDate);
expect(result).toBe(mockResult);
});
```
--------------------------------
### TypeScript: Use untrack for Svelte 5 Rune Warnings
Source: https://github.com/spences10/sveltekit-embed/blob/main/packages/sveltekit-embed/TESTING_STRATEGY.md
This example addresses warnings related to Svelte 5 runes like `$derived` in test files by using the `untrack` function to access derived values without creating reactive dependencies, thus avoiding the warnings.
```typescript
import { untrack } from 'svelte';
// ❌ Direct access causes warnings
expect(derivedValue).toBe(expectedValue);
// ✅ Use untrack to avoid warnings
expect(untrack(() => derivedValue)).toBe(expectedValue);
```
--------------------------------
### Configure Vitest Workspaces for SvelteKit
Source: https://github.com/spences10/sveltekit-embed/blob/main/packages/sveltekit-embed/TESTING_STRATEGY.md
Configures Vitest workspaces to separate client-side, SSR, and server-side Node.js tests within a SvelteKit project. It specifies environments, browser providers, and include/exclude patterns for each test type.
```typescript
// vite.config.ts
test: {
workspace: [
{
// Client-side tests (Svelte components)
extends: './vite.config.ts',
test: {
name: 'client',
environment: 'browser',
browser: {
enabled: true,
provider: 'playwright',
instances: [{ browser: 'chromium' }]
},
include: ['src/**/*.svelte.{test,spec}.{js,ts}'],
exclude: ['src/lib/server/**', 'src/**/*.ssr.{test,spec}.{js,ts}'],
setupFiles: ['./vitest-setup-client.ts'],
},
},
{
// SSR tests (Server-side rendering)
extends: './vite.config.ts',
test: {
name: 'ssr',
environment: 'node',
include: ['src/**/*.ssr.{test,spec}.{js,ts}'],
},
},
{
// Server-side tests (Node.js utilities)
extends: './vite.config.ts',
test: {
name: 'server',
environment: 'node',
include: ['src/**/*.{test,spec}.{js,ts}'],
exclude: [
'src/**/*.svelte.{test,spec}.{js,ts}',
'src/**/*.ssr.{test,spec}.{js,ts}'
],
},
},
],
}
```
--------------------------------
### Embed CodePen Demo
Source: https://github.com/spences10/sveltekit-embed/blob/main/apps/web/src/routes/+page.md
Embeds a CodePen demo using its ID. Supports customization of `height`, `width`, `codePenId`, `tabs`, `clickToLoad`, `editable`, `theme`, `disable_observer`, and `iframe_styles`. The `disable_observer` prop can be passed.
```html
```
```html
```
--------------------------------
### Use AnchorFm Component in SvelteKit
Source: https://github.com/spences10/sveltekit-embed/blob/main/README.md
Demonstrates how to import and use the AnchorFm embed component in a Svelte component, specifying the height and episode URL.
```html
```
--------------------------------
### Test Window/Browser APIs in Node Environment
Source: https://github.com/spences10/sveltekit-embed/blob/main/packages/sveltekit-embed/TESTING_STRATEGY.md
Illustrates how to test functions that rely on browser-specific APIs (like `window.scrollY`) within a Node.js testing environment. It involves mocking the `window` object and its properties to simulate the browser environment.
```typescript
test('handles window.scrollY', () => {
// Mock window.scrollY for Node environment
Object.defineProperty(window, 'scrollY', {
value: 100,
writable: true,
});
const result = checkScrollPosition();
expect(result).toBe(true);
});
```
--------------------------------
### Embed Anchor.fm Episodes in SvelteKit
Source: https://github.com/spences10/sveltekit-embed/blob/main/packages/sveltekit-embed/README.md
Shows how to embed podcast episodes from Anchor.fm using the AnchorFm component from sveltekit-embed. Requires `height` and `episodeUrl` props.
```svelte
```
--------------------------------
### Comprehensive Component Test Structure
Source: https://github.com/spences10/sveltekit-embed/blob/main/packages/sveltekit-embed/TESTING_STRATEGY.md
Provides a detailed structure for comprehensive Svelte component testing, covering various aspects like initial rendering, rune state management, CSS styling, user interactions, content rendering, edge cases, accessibility, component structure, and advanced patterns. Each section includes placeholder tests for different scenarios.
```typescript
describe('Component Name', () => {
describe('Initial Rendering', () => {
// Test all component variants and default states
it('should render with default props', async () => {});
it('should render with custom props', async () => {});
it('should handle missing props gracefully', async () => {});
});
describe('Rune State Management', () => {
// Test reactive state patterns with Svelte 5 runes
it('should manage state with $state rune', async () => {});
it('should test state transitions', async () => {});
it('should handle derived state correctly', async () => {});
});
describe('CSS Classes and Styling', () => {
// Test styling logic and conditional classes
it('should apply correct CSS classes for each variant', async () => {});
it('should test CSS class derivation logic', async () => {});
});
describe('User Interactions', () => {
// Test click, hover, keyboard interactions
it('should handle click events', async () => {});
it('should respond to keyboard input', async () => {});
});
describe('Content Rendering', () => {
// Test different content types and edge cases
it('should render HTML content', async () => {});
it('should handle plain text', async () => {});
it('should handle empty content', async () => {});
it('should handle special characters', async () => {});
});
describe('Edge Cases', () => {
// Test boundary conditions and error states
it('should handle empty props', async () => {});
it('should handle very long content', async () => {});
it('should handle invalid data gracefully', async () => {});
});
describe('Accessibility', () => {
// Test ARIA attributes, semantic structure
it('should have proper ARIA roles', async () => {});
it('should be keyboard accessible', async () => {});
it('should maintain semantic structure', async () => {});
});
describe('Component Structure', () => {
// Test DOM structure and layout
it('should have correct DOM structure', async () => {});
it('should maintain consistent spacing', async () => {});
});
describe('Advanced Patterns', () => {
// Test complex reactive patterns and lifecycle
it('should handle complex state interactions', async () => {});
it('should manage component lifecycle correctly', async () => {});
});
});
```
--------------------------------
### TypeScript: Use Locators Instead of Manual DOM Queries
Source: https://github.com/spences10/sveltekit-embed/blob/main/packages/sveltekit-embed/TESTING_STRATEGY.md
This snippet demonstrates the correct way to interact with elements in tests using locators, which automatically handle retries and DOM updates, contrasting it with the older manual DOM query approach that requires `flushSync`.
```typescript
// ❌ Old approach - manual DOM queries need flushSync
button.click();
flushSync(); // Ensure DOM updates are applied
expect(
container.querySelector('[data-testid="result"]'),
).toBeTruthy();
// ✅ New approach - locators automatically wait
await button.click();
await expect.element(page.getByTestId('result')).toBeInTheDocument();
```
--------------------------------
### Test Reactive State Updates (Svelte 5 Runes)
Source: https://github.com/spences10/sveltekit-embed/blob/main/packages/sveltekit-embed/TESTING_STRATEGY.md
Demonstrates testing reactive state updates using Svelte 5's $state rune. It shows how to render a component, assert initial state, update the state, and verify the UI reflects the changes without needing explicit flushSync calls.
```typescript
test('reactive state updates', async () => {
const props = $state({ count: 0 });
render(Counter, { props });
const counter = page.getByTestId('counter');
await expect.element(counter).toHaveTextContent('0');
props.count = 5;
// No flushSync() needed - locators automatically wait for updates!
await expect.element(counter).toHaveTextContent('5');
});
```
--------------------------------
### Write Descriptive Test Names (TypeScript)
Source: https://github.com/spences10/sveltekit-embed/blob/main/packages/sveltekit-embed/TESTING_STRATEGY.md
Highlights the importance of using clear and descriptive names for test cases to improve readability and understanding of test suite behavior. Contrasts vague names with specific, informative ones.
```typescript
// ❌ Vague test names
test('button works', () => {});
// ✅ Descriptive test names
test('shows loading state when form is submitting', () => {});
test('displays error message when email is invalid', () => {});
```
--------------------------------
### TypeScript Type Definitions for SvelteKit Embed
Source: https://github.com/spences10/sveltekit-embed/blob/main/packages/sveltekit-embed/README.md
Illustrates how to import TypeScript type definitions for props of sveltekit-embed components, such as `YouTubeProps` and `SpotifyProps`, for enhanced type safety.
```typescript
import type { YouTubeProps, SpotifyProps } from 'sveltekit-embed';
```
--------------------------------
### Test Svelte 5 Reactive State Transitions with Runes
Source: https://github.com/spences10/sveltekit-embed/blob/main/packages/sveltekit-embed/TESTING_STRATEGY.md
This TypeScript code demonstrates how to test reactive state transitions using Svelte 5's $state and $derived runes. It includes testing initial states, simulating state changes, and verifying derived state updates using `untrack()` and `flushSync()`.
```typescript
test('should test banner type state transitions', async () => {
let bannerState = $state({
currentType: 'info' as BannerOptions['type'],
previousType: null as BannerOptions['type'] | null,
changeCount: 0,
});
// Derived state for tracking changes
let hasTypeChanged = $derived(
bannerState.currentType !== bannerState.previousType,
);
// Test initial state
expect(untrack(() => hasTypeChanged)).toBe(true);
// Simulate state change
bannerState.previousType = bannerState.currentType;
bannerState.currentType = 'warning';
bannerState.changeCount++;
flushSync();
expect(untrack(() => hasTypeChanged)).toBe(true);
});
```
--------------------------------
### Group Related Tests Using Describe Blocks (TypeScript)
Source: https://github.com/spences10/sveltekit-embed/blob/main/packages/sveltekit-embed/TESTING_STRATEGY.md
Demonstrates how to organize tests into logical groups using `describe` blocks, improving test suite structure and maintainability. Nested `describe` blocks further categorize tests by functionality.
```typescript
describe('ContactForm', () => {
describe('validation', () => {
test('shows error for invalid email', () => {});
test('shows error for empty required fields', () => {});
});
ddescribe('submission', () => {
test('shows loading state during submission', () => {});
test('shows success message on successful submission', () => {});
});
});
```
--------------------------------
### YouTube Props for Embedding
Source: https://github.com/spences10/sveltekit-embed/blob/main/apps/web/src/routes/+page.md
Defines the properties used to configure YouTube embeds, including video and playlist IDs, playback options like autoplay and mute, display controls, branding, aspect ratio, and timestamp skipping.
```typescript
interface YouTubeProps {
youTubeId: string;
listId?: string;
index?: number;
autoPlay?: boolean;
mute?: boolean;
controls?: boolean;
loop?: boolean;
modestBranding?: boolean;
rel?: boolean;
aspectRatio?: string;
skipTo?: { h: number; m: number; s: number };
disable_observer?: boolean;
iframe_styles?: string;
}
```
--------------------------------
### Use Custom Svelte Component
Source: https://github.com/spences10/sveltekit-embed/blob/main/README.md
Illustrates the usage of a custom Svelte component 'MyComponent' with its defined prop 'myComponentId'.
```html
```
--------------------------------
### Embed Gist Snippet
Source: https://github.com/spences10/sveltekit-embed/blob/main/apps/web/src/routes/+page.md
Embeds a GitHub Gist using its URI. Customizable props include `width`, `height`, `gistUri`, and `disable_observer`. The `disable_observer` prop can be passed.
```html
```
```html
```
--------------------------------
### Leverage Locator Auto-Retry Behavior (TypeScript)
Source: https://github.com/spences10/sveltekit-embed/blob/main/packages/sveltekit-embed/TESTING_STRATEGY.md
Explains how SvelteKit testing locators automatically handle retries for assertions, reducing the need for manual synchronization like `flushSync`. Compares the old pattern with manual waits to the new, simpler locator-based approach.
```typescript
// ❌ Old pattern with manual synchronization
test('updates after click', async () => {
render(MyComponent);
const button = page.getByRole('button');
await button.click();
flushSync(); // Usually not needed!
await expect.element(page.getByText('Updated')).toBeInTheDocument();
});
// ✅ New pattern - let locators handle waiting
test('updates after click', async () => {
render(MyComponent);
const button = page.getByRole('button');
await button.click();
// Locators automatically wait for DOM updates
await expect.element(page.getByText('Updated')).toBeInTheDocument();
});
```
--------------------------------
### Test Head Content Generation
Source: https://github.com/spences10/sveltekit-embed/blob/main/packages/sveltekit-embed/TESTING_STRATEGY.md
Tests the generation of head content, specifically the title and meta description tags, for a Svelte component. It uses the `render` function from 'svelte/server' to render the component and asserts the presence of the expected tags in the head.
```typescript
test('generates proper head content', () => {
const { head } = render(SEOComponent, {
props: {
title: 'My Page Title',
description: 'Page description',
},
});
expect(head).toContain('My Page Title');
expect(head).toContain(
'',
);
});
```
--------------------------------
### Test Complex Reactive Logic with Runes
Source: https://github.com/spences10/sveltekit-embed/blob/main/packages/sveltekit-embed/TESTING_STRATEGY.md
Demonstrates comprehensive rune testing for complex reactive logic in SvelteKit components. It covers setting up reactive state, creating derived states, and testing state transitions, ensuring accurate behavior of reactive updates.
```typescript
// ✅ Comprehensive rune testing pattern
test('should test complex reactive logic', async () => {
// Set up reactive state
let componentState = $state({
currentValue: 'initial',
previousValue: null,
changeCount: 0,
});
// Create derived state that mimics component logic
let hasChanged = $derived(
componentState.currentValue !== componentState.previousValue,
);
let isValid = $derived(
componentState.currentValue.length > 0 &&
componentState.changeCount >= 0,
);
// Test initial state
expect(untrack(() => hasChanged)).toBe(true); // null !== 'initial'
expect(untrack(() => isValid)).toBe(true);
// Test state transitions
componentState.previousValue = componentState.currentValue;
componentState.currentValue = 'updated';
componentState.changeCount++;
flushSync(); // Still needed for immediate derived state evaluation
expect(untrack(() => hasChanged)).toBe(true);
expect(untrack(() => isValid)).toBe(true);
expect(componentState.changeCount).toBe(1);
});
```
--------------------------------
### Basic Svelte Component Test with Vitest
Source: https://github.com/spences10/sveltekit-embed/blob/main/packages/sveltekit-embed/TESTING_STRATEGY.md
Demonstrates a basic Svelte component test using Vitest and vitest-browser-svelte. It renders a Svelte component and asserts its content using Playwright locators and expect matchers.
```typescript
import { describe, expect, test } from 'vitest';
import { render } from 'vitest-browser-svelte';
import { page } from '@vitest/browser/context';
import { flushSync } from 'svelte';
import MyComponent from './MyComponent.svelte';
describe('MyComponent', () => {
test('renders with default props', async () => {
render(MyComponent);
const element = page.getByTestId('my-element');
await expect.element(element).toHaveTextContent('Expected Text');
});
});
```
--------------------------------
### Move @next Package to Latest Tag on NPM
Source: https://github.com/spences10/sveltekit-embed/blob/main/README.md
Command to change the distribution tag of a specific version of the sveltekit-embed package from '@next' to 'latest'.
```bash
# authenticate with npm
npm login
# move @next to latest
npm dist-tag add sveltekit-embed@0.0.13 latest
```
--------------------------------
### Embed Spotify with SvelteKit
Source: https://github.com/spences10/sveltekit-embed/blob/main/apps/web/src/routes/+page.md
This component facilitates embedding Spotify content, configurable by Spotify link, dimensions, and observer disabling. It includes custom iframe styles for precise layout control. Props are defined in TypeScript and usage is shown in HTML.
```typescript
spotifyLink: string = '';
height: string = '100%';
width: string = '152px';
disable_observer: boolean = false;
iframe_styles: string = `
border-radius: 0.8rem;
height: ${height};
width: ${width};
`;
```
```html
```
--------------------------------
### Systematically Test Component Variants
Source: https://github.com/spences10/sveltekit-embed/blob/main/packages/sveltekit-embed/TESTING_STRATEGY.md
Provides a method for systematically testing all component variants. It defines an array of variant configurations and iterates through them to render the component with different props, asserting the expected class for each variant.
```typescript
// ✅ Test all component variants systematically
const componentVariants = [
{ type: 'info', expectedClass: 'bg-info' },
{ type: 'warning', expectedClass: 'bg-warning' },
{ type: 'success', expectedClass: 'bg-success' },
{ type: 'error', expectedClass: 'bg-error' },
];
componentVariants.forEach(({ type, expectedClass }) => {
test(`should render ${type} variant correctly`, async () => {
render(Component, { props: { type } });
const element = page.getByRole('alert');
await expect.element(element).toHaveClass(expectedClass);
});
});
```
--------------------------------
### Correctly Accessing Window Properties in Vitest
Source: https://github.com/spences10/sveltekit-embed/blob/main/packages/sveltekit-embed/TESTING_STRATEGY.md
Addresses the "global is not defined" error in Vitest by showing the correct way to access or define global properties like `window.scrollY` in a browser testing context. It recommends using `window` directly or `Object.defineProperty`.
```typescript
// ❌ Don't use global in browser tests
global.window.scrollY = 100;
// ✅ Use window directly or Object.defineProperty
Object.defineProperty(window, 'scrollY', {
value: 100,
writable: true,
});
```
--------------------------------
### Import Custom Component in SvelteKit
Source: https://github.com/spences10/sveltekit-embed/blob/main/README.md
Shows how to import a custom Svelte component ('MyComponent') that has been added to the sveltekit-embed package.
```svelte
import {MyComponent} from 'sveltekit-embed'
```