visit
npm init playwright@latest -- --ct
When the installation ends, there will be a new file in your project called: playwright-ct.config.ts
. This file contains the configuration for the components' testing.For this tutorial, you have to change only one configuration, testDir
property from ./
to ./src
. Playwright uses this configuration to understand where the files used for the components' tests are located. In this example, you'll put the test file in the same folder as the component.
Create a file called Icon.spec.tsx
in the folder src/components/Icon/
, and inside of it, copy this code.
import { expect, test } from '@playwright/experimental-ct-react';
import Icon from './Icon';
test.use({ viewport: { width: 500, height: 500 } });
const props = {
src: 'src',
title: 'title',
}
test('should work', async ({ mount }) => {
const component = await mount(<Icon src={props.src} title={props.title} />);
await expect(component).toHaveAttribute('src', 'src');
await expect(component).toHaveAttribute('title', props.title);
});
You have to import the methods relative to react components from the path @playwright/experimental-ct-react
and import your component.
The test structure is straightforward; using the mount
method, you can render the component in the DOM, and then you can check the result using the Playwright APIs.
For instance, in this case, the test checks if the src
and title
attributes have the correct value.
npx playwright test -c playwright-ct.config.ts
npx playwright show-report
You can find out more info in the official documentation if you want to dive into it.
You can find the code of this post