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
Optimizing Playwright Testing Code
Your existing code is well-structured and readable. However, there are opportunities to improve maintainability, reduce duplication, and enhance performance. Here's a refactored version of your code with explanations for the changes.
Refactored Code
import { test, expect } from '@playwright/test'; const AIRPORT_DETAILS_URL = '/details?cityIata=PAR&airportIcao=CDG#short'; const CARD_HEADINGS = ['Top Destinations', 'Top Aircrafts', 'Busiest Days']; const CARD_CONTENT_SELECTOR = 'div.card-content-wrapper'; const LIST_ITEM_SELECTORS = { bigFont: 'li.big-font.ng-star-inserted', regular: 'li.ng-star-inserted:not(.big-font)', }; const BUSIEST_DAY_CANVAS_ATTRS = { width: '341', height: '215' }; test.describe('Airport Details Tests', () => { test.beforeEach(async ({ page }) => { await page.goto(AIRPORT_DETAILS_URL); }); test('Check major section headings in Airport details', async ({ page }) => { const headingLocators = CARD_HEADINGS.map((heading) => page.getByRole('heading', { name: heading }) ); await expect.poll(async () => await Promise.all(headingLocators.map((locator) => locator.isVisible()))).toEqual(Array(CARD_HEADINGS.length).fill(true)); }); test.describe('Top Destinations and Top Aircrafts cards', () => { const cardIndexes = [0, 1]; cardIndexes.forEach((index) => { test(`Should contain 3 big-font and 7 regular <li> elements in ${CARD_HEADINGS[index]} card`, async ({ page }) => { const wrapper = page.locator(CARD_CONTENT_SELECTOR).nth(index); await expect(wrapper.locator(LIST_ITEM_SELECTORS.bigFont)).toHaveCount(3); await expect(wrapper.locator(LIST_ITEM_SELECTORS.regular)).toHaveCount(7); }); }); }); test('Should contain an image diagram in Busiest Day card with correct attributes', async ({ page }) => { const wrapper = page.locator(CARD_CONTENT_SELECTOR).nth(2); const canvas = wrapper.locator(`canvas[role="img"][width="${BUSIEST_DAY_CANVAS_ATTRS.width}"][height="${BUSIEST_DAY_CANVAS_ATTRS.height}"]`); await expect(canvas).toBeVisible(); // Check actual rendered size with tolerance const box = await canvas.boundingBox(); expect(box?.width).toBeCloseTo(Number(BUSIEST_DAY_CANVAS_ATTRS.width), 1); expect(box?.height).toBeCloseTo(Number(BUSIEST_DAY_CANVAS_ATTRS.height), 1); }); });Key Optimizations and Improvements
-
Extracted Constants:
- Defined constants at the top for URLs, selectors, and expected values. This makes the code more maintainable and easier to update.
-
Improved Heading Visibility Check:
- Replaced the
forloop withPromise.allandexpect.pollto wait for all headings to be visible concurrently. This approach is more efficient and scalable.
- Replaced the
-
Reduced Duplication in Card Tests:
- Introduced a
test.describeblock for related tests (Top Destinations and Top Aircrafts cards). - Used
forEachto iterate over card indexes, eliminating duplicated test code. This pattern makes it easy to add more cards in the future.
- Introduced a
-
Simplified List Item Selectors:
- Stored list item selectors in an object (
LIST_ITEM_SELECTORS) for better organization and reuse.
- Stored list item selectors in an object (
-
Combined Attribute Checks for Canvas:
- Incorporated expected
widthandheightattributes directly into thecanvaslocator. This reduces the number of assertions and makes the intent clearer.
- Incorporated expected
-
Minor Adjustments:
- Used template literals for dynamic test titles in the
forEachloop. - Converted attribute values to numbers when comparing rendered sizes for clarity.
- Used template literals for dynamic test titles in the
Performance Considerations
- Avoid Unnecessary
.nth()Calls: If your page structure allows, consider using more specific selectors instead of relying on.nth()indexing. For example, add adata-testidattribute to your cards and usepage.getByTestId('top-destinations-card'). - Wait for Network Idle (Optional): If your page makes critical API calls, add
waitUntil: 'networkidle'topage.gotooptions to ensure all resources are loaded before running tests.await page.goto(AIRPORT_DETAILS_URL, { waitUntil: 'networkidle' }); - Parallelize Tests: Playwright supports parallel test execution. Run your tests with multiple workers (
npx playwright test --workers=4) to speed up the suite.
Best Practices
- Use Descriptive Test Titles: Ensure each test title clearly states the expected behavior.
- Leverage Playwright's Auto-Retry: Assertions like
toBeVisible()already retry. Avoid adding unnecessarywaitFor()calls. - Keep Tests Independent: Ensure no test relies on the state modified by another test. Use
test.beforeEachwisely.
By applying these optimizations, your test suite becomes more maintainable, efficient, and scalable. Happy testing! 🚀
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.