To run unit tests using Playwright, follow these steps:
-
Install Dependencies: Ensure you have all the necessary dependencies installed. You can install them using npm or yarn:
npm install # or yarn install
-
Run Tests in UI mode: for running test in UI mode (helpful for debugging and running tests on watch mode) :
npm run test:e2e:watch
-
Run tests in headless mode:
npm run test:e2e
To write unit tests using Playwright, follow these guidelines:
-
Create Test Files: Test files should be placed in the
playwright/e2e
directory -
Import Playwright: Import the necessary Playwright modules at the beginning of your test files:
import { test, expect } from "@playwright/test";
-
Write Test Cases: Use the
test
function to define individual test cases. Each test case should have a descriptive name and a callback function containing the test logic:test("should display the correct title", async ({ page }) => { await page.goto("https://example.com"); const title = await page.title(); expect(title).toBe("Example Domain"); });
-
Use Assertions: Use Playwright's built-in assertions to verify the expected outcomes:
expect(await page.textContent("h1")).toBe("Example Domain");
-
Run Setup and Teardown: Use hooks like
beforeAll
,beforeEach
,afterAll
, andafterEach
to run setup and teardown logic:test.beforeEach(async ({ page }) => { await page.goto("https://example.com"); });
For more detailed information, refer to the Playwright documentation.