How I can optimize my Playwright testing code import { test, expect } from…
- User
How I can optimize my Playwright testing code
import { test, expect } from '@playwright/test';
test.describe('Airport Details Tests', () => { test.beforeEach(async ({ page }) => { await page.goto('/details?cityIata=PAR&airportIcao=CDG#short'); });
test('Check major section headings in Airport details', async ({ page }) => { const headings = ['Top Destinations', 'Top Aircrafts', 'Busiest Days'];
for (const heading of headings) { await expect(page.getByRole('heading', { name: heading })).toBeVisible(); }});
test('Should contain 3 big-font and 7 regular elements in Top Destination card', async ({ page }) => { const wrapper = page.locator('div.card-content-wrapper').nth(0);
// Locate all <li> elements with both classes const bigFontItems = wrapper.locator('li.big-font.ng-star-inserted'); await expect(bigFontItems).toHaveCount(3); // Locate all <li> elements with ONLY ng-star-inserted (but NOT big-font) const regularItems = wrapper.locator('li.ng-star-inserted:not(.big-font)'); await expect(regularItems).toHaveCount(7);});
test('Should contain 3 big-font and 7 regular elements in Top Aircrafts card', async ({ page }) => { const wrapper = page.locator('div.card-content-wrapper').nth(1);
// Locate all <li> elements with both classes const bigFontItems = wrapper.locator('li.big-font.ng-star-inserted'); await expect(bigFontItems).toHaveCount(3); // Locate all <li> elements with ONLY ng-star-inserted (but NOT big-font) const regularItems = wrapper.locator('li.ng-star-inserted:not(.big-font)'); await expect(regularItems).toHaveCount(7);});
test('Should contain an image diagram in Busiest Day card with correct attributes', async ({ page }) => { const wrapper = page.locator('div.card-content-wrapper').nth(2); const canvas = wrapper.locator('canvas[role="img"]'); await expect(canvas).toBeVisible();
// Check declared attributes await expect(canvas).toHaveAttribute('width', '341'); await expect(canvas).toHaveAttribute('height', '215'); // Check actual rendered size const box = await canvas.boundingBox(); expect(box?.width).toBeCloseTo(341, 1); // 1 pixel tolerance expect(box?.height).toBeCloseTo(215, 1); // 1 pixel tolerance}); });
- Assistant
Okay, let's optimize this Playwright code. The main areas for improvement are:
- Locator Strategy: Relying on
.nth()is brittle. If the order of cards changes, or new cards are added, your tests will break or test the wrong thing. We should use more specific and robust locators, ideally tied to visible text like the headings. - Repetition (DRY - Don't Repeat Yourself): Tests 2 and 3 ("Top Destinations" and "Top Aircrafts") have almost identical logic. This can be parameterized or put into a helper function.
- CSS Class Dependency: Using classes like
.ng-star-insertedties your tests tightly to the specific framework implementation (Angular in this case). While sometimes unavoidable, try to minimize this if possible..big-fontis slightly better as it might represent a visual state, but still CSS-dependent. - Readability & Maintainability: Using constants for magic numbers (like counts and dimensions) makes the tests easier to read and update.
Here's the refactored code incorporating these optimizations:
import { test, expect } from '@playwright/test'; // --- Constants for better maintainability --- const TARGET_URL = '/details?cityIata=PAR&airportIcao=CDG#short'; const EXPECTED_HEADINGS = ['Top Destinations', 'Top Aircrafts', 'Busiest Days']; const LIST_ITEM_COUNTS = { bigFont: 3, regular: 7, }; const BUSIEST_DAY_CANVAS = { width: 341, height: 215, tolerance: 1, // Pixel tolerance for bounding box check }; // --- Helper Function to get Card Wrapper by Heading --- // This assumes a common structure like: // <some-card-container> // <heading>{headingText}</heading> // <div class="card-content-wrapper">...</div> // </some-card-container> // Adjust the locator '.card-content-wrapper' relative to the heading if needed. // Example: If wrapper is a sibling: headingLocator.locator('xpath=following-sibling::div[contains(@class, "card-content-wrapper")]') // Example: If wrapper is inside a parent container: page.locator(`section:has(:text("${headingText}"))`).locator('.card-content-wrapper') const getCardWrapperByHeading = (page, headingText: string) => { const headingLocator = page.getByRole('heading', { name: headingText, exact: true }); // Assuming the wrapper is the direct next sibling element or a child of a common parent // This is MORE ROBUST than nth() but might need adjustment based on your exact DOM structure. // Option 1: Common Parent (adjust 'article' or 'section' as needed) return page.locator(`article:has(> h2:has-text("${headingText}"))`).locator('div.card-content-wrapper'); // Option 2: Sibling (less common for semantic structure, but possible) // return headingLocator.locator('xpath=following-sibling::div[contains(@class, "card-content-wrapper")]'); }; // --- Test Suite --- test.describe('Airport Details Tests', () => { test.beforeEach(async ({ page }) => { await page.goto(TARGET_URL); // Optional: Wait for a key element to ensure the page section is loaded // await expect(page.getByRole('heading', { name: 'Top Destinations' })).toBeVisible(); }); test('Check major section headings are visible', async ({ page }) => { // Use Promise.all for potentially faster parallel checks (though overhead might negate gains for few items) await Promise.all( EXPECTED_HEADINGS.map(heading => expect(page.getByRole('heading', { name: heading })).toBeVisible() ) ); }); // --- Parameterized Test for List Item Counts --- const cardTestCases = [ { heading: 'Top Destinations' }, { heading: 'Top Aircrafts' }, ]; for (const testCase of cardTestCases) { test(`Card "${testCase.heading}" should contain ${LIST_ITEM_COUNTS.bigFont} big-font and ${LIST_ITEM_COUNTS.regular} regular <li> elements`, async ({ page }) => { // Use the helper function to get the correct card wrapper based on its heading const wrapper = getCardWrapperByHeading(page, testCase.heading); await expect(wrapper).toBeVisible(); // Ensure the card itself is found and visible // Locate <li> elements within THIS specific card's wrapper // NOTE: Using .ng-star-inserted is still a dependency on Angular implementation details. // If possible, find more semantic attributes or structures. const bigFontItems = wrapper.locator('li.big-font.ng-star-inserted'); await expect(bigFontItems).toHaveCount(LIST_ITEM_COUNTS.bigFont); const regularItems = wrapper.locator('li.ng-star-inserted:not(.big-font)'); await expect(regularItems).toHaveCount(LIST_ITEM_COUNTS.regular); // Optional stricter check: Ensure total count matches // const allItems = wrapper.locator('li.ng-star-inserted'); // await expect(allItems).toHaveCount(LIST_ITEM_COUNTS.bigFont + LIST_ITEM_COUNTS.regular); }); } test('Card "Busiest Days" should contain an image diagram with correct attributes and size', async ({ page }) => { const wrapper = getCardWrapperByHeading(page, 'Busiest Days'); await expect(wrapper).toBeVisible(); const canvas = wrapper.locator('canvas[role="img"]'); await expect(canvas).toBeVisible(); // Check declared attributes using constants await expect(canvas).toHaveAttribute('width', String(BUSIEST_DAY_CANVAS.width)); await expect(canvas).toHaveAttribute('height', String(BUSIEST_DAY_CANVAS.height)); // Check actual rendered size using constants and tolerance const box = await canvas.boundingBox(); expect(box?.width).toBeCloseTo(BUSIEST_DAY_CANVAS.width, BUSIEST_DAY_CANVAS.tolerance); expect(box?.height).toBeCloseTo(BUSIEST_DAY_CANVAS.height, BUSIEST_DAY_CANVAS.tolerance); }); });Explanation of Changes:
- Constants: Defined constants (
TARGET_URL,EXPECTED_HEADINGS,LIST_ITEM_COUNTS,BUSIEST_DAY_CANVAS) at the top. This makes the tests easier to read and update if these values change. - Robust Locators (
getCardWrapperByHeading):- Introduced a helper function
getCardWrapperByHeading. - This function first finds the unique heading text (
page.getByRole('heading', { name: headingText, exact: true })). - Then, it finds the associated
div.card-content-wrapperrelative to that heading. The example usespage.locator(\article:has(> h2:has-text("${headingText}"))`).locator('div.card-content-wrapper'). This assumes your HTML structure is something likeHeading.... **You might need to adjust the secondlocatorpart based on your actual DOM structure** (e.g., using XPathfollowing-siblingor different parent selectors). This is *significantly* more robust than relying on.nth()`.
- Introduced a helper function
- Parameterized Tests:
- Created an array
cardTestCasesdefining the headings for the cards that share the same list item validation logic. - Used a
for...ofloop to iterate through these cases and generate atestfor each one. - The test name is dynamically generated for clarity (
Card "${testCase.heading}" should contain...). - Inside the loop, it calls
getCardWrapperByHeadingwith the specific heading and uses the constants for assertions (LIST_ITEM_COUNTS). This eliminates code duplication.
- Created an array
- Improved Assertions:
- The heading check now uses
Promise.allfor potentially slightly faster execution (though negligible for 3 items). - The canvas size check uses
toBeCloseTowith a defined tolerance, which is good practice for rendered dimensions that might vary slightly. - Added
await expect(wrapper).toBeVisible();within the parameterized tests and the Busiest Days test to ensure the correct card was located before checking its contents.
- The heading check now uses
- Comments and Clarity: Added comments explaining the locator strategy and potential adjustments needed.
Further Potential Optimizations (Depending on Context):
data-testidAttributes: The most robust way to locate elements is usingdata-testid(or similardata-*) attributes added specifically for testing purposes in your application's HTML. If you have control over the frontend code, this is highly recommended. Locators would becomepage.getByTestId('top-destinations-card'), etc.- Page Object Model (POM): For larger test suites, encapsulating page elements and interactions within Page Object classes improves organization and maintainability significantly.
- API Calls: If the data displayed (like top destinations) is static or predictable, consider if some checks could be done via API calls instead of UI interaction, which is usually faster and less flaky. However, these tests are specifically checking the UI rendering, so UI interaction is necessary here.
- Reduce
ng-star-insertedDependency: Investigate if the<li>elements have other, more stable attributes or structures you could select by, reducing the reliance on the Angular-specific class.
- Locator Strategy: Relying on
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.