Skip to content
The Chat Archive
llama-4-maverick-03-26-experimental· Meta LMArena Human Preference 140K

How I can optimize my Playwright testing code import { test, expect } from…

  1. 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
    

    }); });

  2. 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

    1. Extracted Constants:

      • Defined constants at the top for URLs, selectors, and expected values. This makes the code more maintainable and easier to update.
    2. Improved Heading Visibility Check:

      • Replaced the for loop with Promise.all and expect.poll to wait for all headings to be visible concurrently. This approach is more efficient and scalable.
    3. Reduced Duplication in Card Tests:

      • Introduced a test.describe block for related tests (Top Destinations and Top Aircrafts cards).
      • Used forEach to iterate over card indexes, eliminating duplicated test code. This pattern makes it easy to add more cards in the future.
    4. Simplified List Item Selectors:

      • Stored list item selectors in an object (LIST_ITEM_SELECTORS) for better organization and reuse.
    5. Combined Attribute Checks for Canvas:

      • Incorporated expected width and height attributes directly into the canvas locator. This reduces the number of assertions and makes the intent clearer.
    6. Minor Adjustments:

      • Used template literals for dynamic test titles in the forEach loop.
      • Converted attribute values to numbers when comparing rendered sizes for clarity.

    Performance Considerations

    1. Avoid Unnecessary .nth() Calls: If your page structure allows, consider using more specific selectors instead of relying on .nth() indexing. For example, add a data-testid attribute to your cards and use page.getByTestId('top-destinations-card').
    2. Wait for Network Idle (Optional): If your page makes critical API calls, add waitUntil: 'networkidle' to page.goto options to ensure all resources are loaded before running tests.
      await page.goto(AIRPORT_DETAILS_URL, { waitUntil: 'networkidle' });
      
    3. 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

    1. Use Descriptive Test Titles: Ensure each test title clearly states the expected behavior.
    2. Leverage Playwright's Auto-Retry: Assertions like toBeVisible() already retry. Avoid adding unnecessary waitFor() calls.
    3. Keep Tests Independent: Ensure no test relies on the state modified by another test. Use test.beforeEach wisely.

    By applying these optimizations, your test suite becomes more maintainable, efficient, and scalable. Happy testing! 🚀

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.