š© Why Hooks? The Magic Behind the Scenes
Luckily, Playwright offers a powerful feature to solve this ā hooks.
Imagine youāre hosting a party š„³. You wouldnāt clean the house after every guest leaves, right? Instead, youād:
šļø Setup once (decorate, cook food) ā beforeAll
šļø Clean as you go (refill snacks, wipe spills) ā beforeEach/afterEach
š£Nuclear cleanup after everyone leaves ā afterAll
In testing terms: Hooks automate repetitive tasks so your tests can focus on what matters.
š® Meet the 4 Hooks
š Your Code in Action: Login/Logout Flow
Letās automate a shopping site test (your code!).
Step 1: beforeEach ā The āWelcome Matā
Why it rocks: Every test starts fresh, logged in, and cookie-free!
test.beforeEach(async ({ page }) => {
// šÆ Navigate to login
await page.goto('https://www.automationexercise.com/login');
// šŖ Crush cookies (popup)
await page.locator('p.fc-button-label').nth(0).click();
// š Login steps
await page.locator('[data-qa="login-email"]').fill('demoaccount@example.com');
await page.getByPlaceholder('Password').fill('password01');
await page.getByRole('button', { name: 'Login' }).click();
// ā
Verify login success
await expect(page).toHaveURL('https://www.automationexercise.com/');
});
Step 2: afterEach ā The āGoodbye Kissā
test.afterEach(async ({ page }) => {
// š Logout after every test
await page.locator('[href="/logout"]').click();
});
Why it matters: No test messes with anotherās session!
Step 3: Tests ā Lean & Mean!
// š” Test 1: Check homepage content
test('validate home content after login', async ({ page }) => {
await expect(page.locator('div.features_items')).toBeVisible();
await expect(page.locator('h2:has-text("Features Items")')).toBeVisible();
});
// š Test 2: Add to cart
test('Add product to the cart', async ({ page }) => {
await page.locator('div.productinfo a').first().click();
await page.locator('[data-dismiss="modal"]').click();
});
No login code! Hooks handle it all. š
š¹ Watch the Code in Action!
š¤ Quiz Time! Which Hook Would You Use?
Seed a database before all tests ā beforeAll
Reset a form after each test ā afterEach
Close all browser tabs after the entire suite ā afterAll
(Howād you do? Comment below! š¬)
š” Pro Tips for Hook Masters
Avoid waitForTimeout: Use waitForLoadState or assertions instead.
Group hooks with test.describe: Scope hooks to specific test groups.
Use beforeAll sparingly: Shared state can cause test pollution!
š Conclusion: Hooked Yet?
Hooks turn chaotic test suites into well-oiled machines. Start with beforeEach/afterEach, then explore beforeAll/afterAll for big setups.
Your code already nails the essentials ā now go automate all the things!
Comments
Post a Comment