How to verify a component is visible?

57 Views Asked by At

I'm trying to write a test on my SvelteKit project with playwrite.

Let's say I have this +page.svelte:

<script>
  import A from './A.svelte'
  import B from './B.svelte'

</script>

<A />   

<B />

I would like to write a test to verify that A and B components are visible (and not C as it is not imported and used by my page).

I'm searching for something like getBySvelteComponent in the following example:

import { expect, test } from '@playwright/test';

test('The page should contain the A and B components but not C', async ({ page }) => {
  await page.goto('/');

  await expect(page.getBySvelteComponent(A)).toBeVisible();
  await expect(page.getBySvelteComponent(B)).toBeVisible();
  await expect(page.getBySvelteComponent(C)).not.toBeVisible();
});

Is there a way to achieve what I'm trying to do?

1

There are 1 best solutions below

0
g0rb On BEST ANSWER

I don't believe you can query for a component using the class instances in Playwright. Personally, I use data-test selectors when trying to query Svelte elements in Playwright.

You can couple that with the Playwright locator assertion that verifies an element is hidden. https://playwright.dev/docs/api/class-locatorassertions#locator-assertions-to-be-hidden

import { expect, test } from '@playwright/test';

test('displays the A component and hides C', async ({ page }) => {
  await page.goto('/');

  const aComponent = page.locator('[data-testid="myComponentA"]');
  await expect(aComponent).toBeVisible();

  const cComponent = page.locator('[data-testid="myComponentC"]');
  await expect(cComponent).toBeHidden();
});
// A.svelte

<div data-testid="myComponentA">
...
</div>
// C.svelte

<div data-testid="myComponentC">
...
</div>

You can take it one step further and use the getByTestId page API for visible elements. https://playwright.dev/docs/api/class-page#page-get-by-test-id

import { expect, test } from '@playwright/test';

test('displays the A component and hides C', async ({ page }) => {
  await page.goto('/');

  await expect(page.getByTestId('myComponentA').toBeVisible();
  
  const cComponent = page.locator('[data-testid="myComponentC"]');
  await expect(cComponent).toBeVisible();
});