Rayrun

How do I use Playwright to test Svelte components?

Answer

Testing Svelte Components with Playwright

First, you need to install Playwright Test for components for Svelte. Run npm init playwright@latest -• --ct in your terminal. This command creates several files in your workspace, including index.html and index.ts.

Next, create a test file named App.spec.ts in your project's src directory. Here's how you can import the necessary functions from @playwright/experimental-ct-svelte and your Svelte component:

import { test, expect } from '@playwright/experimental-ct-svelte';
import MyComponent from './MyComponent.svelte';

Now, you can define a test case that mounts your Svelte component and asserts its behavior. Here's an example:

test.use({ viewport: { width: 500, height: 500 } });

test('should display greeting', async ({ mount }) => {
  const component = await mount(MyComponent);
  await expect(component).toContainText('Hello World!');
});

test('should update name on button click', async ({ mount }) => {
  const component = await mount(MyComponent);
  const button = await component.locator('button');
  
  // Click button
  await button.click();
  
  // Assert name has been updated
  await expect(component).toContainText('Hello Alice!');
});

Finally, run your tests using npm run test-ct. You can also configure reporting options or specify which browsers to use for testing by referring to the Playwright config documentation. Happy testing with Playwright!

Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

TwitterGitHubLinkedIn
AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email [email protected].