-
Select the component you want to write tests for
-
Inside the component folder, create the
__tests__folder and create a file inside it with the following name<ComponentName>.visual.test.tsx -
Writing a test:
NOTE: Add
await defaultDelay()between mounting and testing routine in every test with animation. It is necessary because of testing during animation in progress is unstable.Capture a screenshot, by default in light theme only:
import React from 'react'; import {expect} from '@playwright/experimental-ct-react'; import {MyComponent} from '../MyComponent'; import {test} from '~playwright/core'; test('test description', async ({page, mount, defaultDelay}) => { // mount the component const component = await mount(<MyComponent props={props} />); // default delay to bypass animation issues await defaultDelay(); // capture the screenshot await expect(component).toHaveScreenshot(); });
You can also capture screenshots both in dark and light themes:
import React from 'react'; import {MyComponent} from '../MyComponent'; import {test} from '~playwright/core'; test('test description', async ({page, mount, expectScreenshot, defaultDelay}) => { // mount the component await mount(<MyComponent props={props} />); // default delay to bypass animation issues await defaultDelay(); // capture the screenshot await expectScreenshot(); });
If you need to do any actions with the component:
import React from 'react'; import {MyComponent} from '../MyComponent'; import {test} from '~playwright/core'; test('test description', async ({page, mount, expectScreenshot, defaultDelay}) => { // mount the component const component = await mount(<MyComponent props={props} />); // default delay to bypass animation issues await defaultDelay(); // the action await component.click(); // capture the screenshot await expectScreenshot({component}); });
Group of tests.
test.describe('Name group tests', () => { test('1', ...); test('2', ...); ... test('10', ...) });
-
Run tests
npm run playwright:install npm run playwright
If you are using system other than Linux, then you need to run tests via docker command:
npm run playwright:docker
npm run playwright:installcommand must be run only once on initial setup -
Update screenshots if needed
npm run playwright:update
Or
npm run playwright:docker:update
-
In the folder
__snapshots__, which is on the same level as the__tests__folder, the folder<Component name>.visual.test.tsx-snapshots, will contain screenshots
npm run playwright:install- install playwright browsers and dependenciesnpm run playwright- run testsnpm run playwright:update- update screenshotsnpm run playwright:clear-cache- clear cache vitenpm run playwright:docker- run tests using dockernpm run playwright:docker:update- update screenshots using dockernpm run playwright:docker:clear-cache- clear node_modules cache for docker container and clear cache vitenpx playwright show-report ./playwright-report-docker- show report