<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Marcin Michalak  on Medium]]></title>
        <description><![CDATA[Stories by Marcin Michalak  on Medium]]></description>
        <link>https://medium.com/@marcinet?source=rss-ad722d8efa1d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*XIa6bwSRYUExi_Fl</url>
            <title>Stories by Marcin Michalak  on Medium</title>
            <link>https://medium.com/@marcinet?source=rss-ad722d8efa1d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 22:16:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@marcinet/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Advanced Playwright: Implementing the Asynchronous Factory Pattern for Page Objects]]></title>
            <link>https://medium.com/@marcinet/advanced-playwright-implementing-the-asynchronous-factory-pattern-for-page-objects-1a3d067499d4?source=rss-ad722d8efa1d------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a3d067499d4</guid>
            <category><![CDATA[test-automation-framework]]></category>
            <category><![CDATA[playwright-test]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[playwright-automation]]></category>
            <category><![CDATA[software-test-automation]]></category>
            <dc:creator><![CDATA[Marcin Michalak ]]></dc:creator>
            <pubDate>Thu, 09 Jul 2026 09:48:56 GMT</pubDate>
            <atom:updated>2026-07-09T09:48:56.393Z</atom:updated>
            <content:encoded><![CDATA[<h3>Build a bulletproof, AI-agent-friendly abstract base page class to have a clear implementation structure and avoid flakiness.</h3><p>Automated end-to-end testing relies heavily on the reliability and clarity of its framework. Are you frustrated with <strong>flaky test runs</strong> because a page wasn’t ready, or <strong>chaotic, inconsistent PageObject implementations</strong> and usage across your team?</p><p>Here is a unified class structure that fixes both issues by pairing an <strong>Asynchronous Factory Method</strong> pattern with an <strong>Abstract Base Page</strong>.</p><h4>The High-Level Overview</h4><p>If you want to bypass standard constructor limitations and ensure your tests only run against 100% stable pages, this pattern lets you initialize page objects in a single line of code:</p><pre>const homePage = await HomePage.init(page);</pre><p>and use it in the test:</p><pre>test(&#39;should initialize HomePage and navigate to Dynamic ID Page&#39;,<br>        async ({ page }) =&gt; {<br>            // Use the async factory instantiation pattern - checks that<br>            // the page is fully loaded.<br>            const homePage = await HomePage.init(page);<br><br>            // Do some extra checks that might not make sense in all cases.<br>            await expect(homePage.dynamicIDLink).toBeVisible();<br><br>            // Perform interaction which returns another strongly typed<br>            // Page Model via its factory.<br>            const dynamicIDPage = await homePage.openDynamicIDPage();<br><br>            // Perform operations on the new page - we know it&#39;s fully loaded.<br>            await expect(dynamicIDPage.buttonWithDynamicID)<br>                .toHaveText(&#39;Button with Dynamic ID&#39;);<br>            await dynamicIDPage.buttonWithDynamicID.click();<br>    });</pre><h3>The Architecture at a Glance</h3><p>When you execute .init(), the framework handles the object lifecycle behind the scenes in three distinct phases:</p><ol><li><strong>Guarded Construction:</strong> The framework completely hides the standard new PageObject() constructor. It cannot be called directly from test files, eliminating uninitialized or partially-loaded objects.</li><li><strong>Implicit Synchronization:</strong> The static init() method automatically runs a custom, mandatory waitUntilLoaded() hook. The test execution pauses until the page fulfills its unique readiness criteria.</li><li><strong>Deterministic Handoff:</strong> The fully formed, verified Page Object is returned to the test script. You can interact with its elements safely without fear of race conditions, lazy-loading glitches, or stale references.</li></ol><h4>Why Standard Page Objects are not good enough</h4><p>To understand why this architecture is necessary, we have to look at the limitations of standard TypeScript classes within automation.</p><p>In JavaScript and TypeScript, <strong>constructors cannot be asynchronous</strong>. This creates a fundamental design conflict for end-to-end testing, because web pages are inherently asynchronous.</p><p>When you use a <strong>traditional Page Object Model (POM)</strong>, you are usually forced into one of two anti-patterns:</p><ul><li><strong>The “Naked” Constructor:</strong> You put element locators in the constructor, but you can’t await page synchronization. The test proceeds immediately, leading to intermittent flakiness if elements take a few milliseconds to render.</li><li><strong>The Two-Step Init:</strong> You instantiate the object and then manually call a secondary setup method on the next line:</li></ul><pre>const homePage = new HomePage(page);<br>await homePage.waitForReady(); // Easy to forget, leading to fragile frameworks</pre><p>By leveraging an <strong>Asynchronous Factory Method</strong>, we wrap the object creation and the asynchronous readiness checks into a single atomic operation.</p><h4>1. The Blueprint: The Abstract Base Page</h4><p>The BasePage serves as our framework&#39;s infrastructure layer. It enforces strict compile-time guardrails so developers cannot mistakenly instantiate an uninitialized or generic page. It also leverages Playwright&#39;s native test.step functionality to put initialization info in the logs.</p><pre># BaseClass.ts<br>import { Page, Locator, test } from &#39;@playwright/test&#39;;<br><br>// Unique symbol to guarantee thread-safe internal instantiation.<br>const INIT_TOKEN = Symbol(&#39;PageInitToken&#39;);<br><br>export abstract class BasePage {<br>    protected page: Page;<br><br>    // A shared getter. No &quot;!&quot; needed, no initialization in the constructor.<br>    // Automatically enforces accessibility standards by looking for the<br>    // semantic role.<br>    public get navHeader(): Locator {<br>        return this.page.getByRole(&#39;navigation&#39;);<br>    }<br><br>    // Examples of a page-specific element getters. These are on EVERY page.<br>    // Makes sure &#39;Home&#39; link is within the navigation header in a list.<br>    public get homeLink(): Locator {<br>        return this.navHeader<br>            .getByRole(&#39;list&#39;).getByRole(&#39;link&#39;, { name: &#39;Home&#39; });<br>    }<br><br>    public get resourcesLink(): Locator {<br>        return this.navHeader<br>            .getByRole(&#39;list&#39;).getByRole(&#39;link&#39;, { name: &#39;Resources&#39; });<br>    }<br><br>    /** Guarded Constructor (only accessible internally via the factory) */<br>    protected constructor(page: Page, token: typeof INIT_TOKEN) {<br>        this.page = page;<br>    }<br><br>    /** ALWAYS use the `init()` method instead of the constructor.<br>     * The Strongly-Typed Asynchronous Factory Method.<br>     * Initializes the page object and ensures that the page is fully loaded<br>     * before returning the instance.<br>     */<br>    public static async init&lt;T extends BasePage&gt;(<br>        this: { prototype: T } &amp; Function,<br>        page: Page<br>    ): Promise&lt;T&gt; {<br>        const pageName = this.name;<br><br>        // Wrap waitUntilLoaded() execution in a Playwright step for native<br>        // reporting logs.<br>        return await test.step(`[POM] Initialize ${pageName}`, async () =&gt; {<br>            // Cast &#39;this&#39; to a generic constructable type to bypass the <br>            // abstract blockade.<br>            const ConcreteConstructor =<br>                this as unknown as new (page: Page, token: any) =&gt; T;<br>            <br>            // Instantiate safely<br>            const instance = new ConcreteConstructor(page, INIT_TOKEN);<br>            // Make sure page is fully loaded. Avoids flakiness in tests - <br>            // this is the key to the async factory pattern<br>            await instance.waitUntilLoaded();<br>            return instance;<br>        });<br>    }<br><br>    /** Every page MUST define its unique readiness criteria in<br>     * waitUntilLoaded. */<br>    protected abstract waitUntilLoaded(): Promise&lt;void&gt;;<br>}</pre><h4>2. The Implementation: Concrete Page Objects</h4><p>Now, look at how clean our specific page objects become. Because selectors are evaluated lazily through TypeScript getters, the subclass requires zero constructors and zero lifecycle hooks. It seamlessly inherits navHeader from the base class and focuses strictly on its own elements and unique loading criteria.</p><p>The BaseClass is used to create a page class, e.g. HomePage:</p><pre># HomePage.ts<br>/** HomePage class extends the abstract `BasePage`.<br> * Inherits the (non-callable) constructor and `init()` method.<br> * Just implement the page-specific getters (locators)<br> * and readiness checks in `waitUntilLoaded()`.<br> */<br>export class HomePage extends BasePage {<br>    public get heading(): Locator {<br>        return this.page.getByRole(&#39;heading&#39;,<br>            { name: &#39;UI Test Automation Playground&#39;, level: 1 });<br>    }<br><br>    public get cubeImage(): Locator {<br>        return this.page.getByRole(&#39;img&#39;, { name: &#39;Responsive Image&#39; });<br>    }<br><br>    // Verify the link is under the H3 heading.<br>    public get dynamicIDLink(): Locator {<br>        return this.page<br>            .getByRole(&#39;heading&#39;, { name: &#39;Dynamic ID&#39;, level: 3 })<br>            .getByRole(&#39;link&#39;, { name: &#39;Dynamic ID&#39; });<br>    }<br><br>    public async openDynamicIDPage(): Promise&lt;DynamicIDPage&gt; {<br>        await this.dynamicIDLink.click();<br>        return await DynamicIDPage.init(this.page);<br>    }<br><br>    protected async waitUntilLoaded(): Promise&lt;void&gt; {<br>        // Make sure the heading and image are visible<br>        // before considering the page fully loaded.<br>        await this.cubeImage.scrollIntoViewIfNeeded();<br>        await expect(this.heading).toBeVisible();<br>        await expect(this.cubeImage).toBeVisible();<br>        // Make sure it&#39;s fully loaded in case of lazy-loading.<br>        await expect<br>            .poll(async () =&gt;<br>                this.cubeImage.evaluate((el) =&gt; {<br>                    const img = el as HTMLImageElement;<br>                    return img.complete &amp;&amp; img.naturalWidth &gt; 0;<br>                })<br>            )<br>            .toBe(true);<br>    }<br>}</pre><h4>3. The Payoff: Writing Linear, Deterministic Tests</h4><p>With this structure, you can write tests easily — just init() the page-object and start operating on the stable page. Here’s (again) <strong>a sample test</strong>:</p><pre>test.describe(&#39;UI Test Playground - Static Factory POM Demo&#39;, () =&gt; {<br>    test.beforeEach(async ({ page }) =&gt; {<br>        // Navigate to the playground app URL.<br>        await page.goto(&#39;http://uitestingplayground.com/&#39;);<br>    });<br><br>    test(&#39;should initialize HomePage and navigate to Dynamic ID Page&#39;,<br>        async ({ page }) =&gt; {<br>            // Use the async factory instantiation pattern - checks that<br>            // the page is fully loaded.<br>            const homePage = await HomePage.init(page);<br><br>            // Do some extra checks that might not make sense in all cases.<br>            await expect(homePage.dynamicIDLink).toBeVisible();<br><br>            // Perform interaction which returns another strongly typed<br>            // Page Model via its factory.<br>            const dynamicIDPage = await homePage.openDynamicIDPage();<br><br>            // Perform operations on the new page - we know it&#39;s fully loaded.<br>            await expect(dynamicIDPage.buttonWithDynamicID)<br>                .toHaveText(&#39;Button with Dynamic ID&#39;);<br>            await dynamicIDPage.buttonWithDynamicID.click();<br>    });<br>});</pre><h4>Clean Reporting Out of the Box</h4><p>When you look at your Playwright HTML report after a test run, you will see clean, collapsible logs indicating exactly where your pages were instantiated:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TaD_2ztpyvwr6Cp0-1xzew.png" /></figure><h4>Why AI Agents Love This Structure</h4><p>Beyond human readability, this pattern provides a massive advantage when integrating AI coding assistants (like GitHub Copilot or custom LLM agents) into your QA workflow.</p><p>AI models thrive on strong constraints. When you ask an AI agent to build a new page object using a loose, traditional POM framework, it will often hallucinate custom setup methods, mix up constructor logic, or skip synchronization steps entirely.</p><p>By contrast, this architecture establishes an unyielding contract:</p><ol><li><strong>The Abstract Enforcement:</strong> Because waitUntilLoaded() is defined as protected abstract, the TypeScript compiler strictly prevents the code from compiling unless the developer (or the AI) defines the page readiness criteria.</li><li><strong>Contextual Clues:</strong> The pattern explicitly guides the LLM to structure its output cleanly into three distinct domains: element getters, actionable methods, and synchronization rules.</li></ol><p>The result? Far <strong>fewer hallucinations</strong> and highly <strong>predictable code generation</strong>.</p><h3>Summary of Benefits</h3><p>By pairing an asynchronous abstract factory pattern with TypeScript getters, your Playwright framework gains three major benefits:</p><ul><li><strong>Zero Flakiness:</strong> Tests never attempt to interact with elements on a page that hasn’t finished loading or updating its state. Getters always fetch the absolute freshest state of the DOM.</li><li><strong>No Boilerplate:</strong> Say goodbye to complex super(page) forwarding, manual constructor chains, or forgetting to call secondary init() methods inside every single test file.</li><li><strong>Compile-Time Safety &amp; Native Logs:</strong> The code structure satisfies strict type-checking while utilizing Playwright’s test.step() to output clean logs directly inside your native execution tree.</li></ul><h3>Full source code on GitHub</h3><p>Check the full source code on my <a href="https://github.com/marcinet/playwright-async-factory-pom">GitHub repo</a>.</p><p><em>Enjoyed this breakdown? Connect with me on </em><a href="https://www.linkedin.com/in/marcin-michalak1/"><em>LinkedIn</em></a><em> to discuss effective test automation frameworks!</em></p><blockquote>Note: For the pages and test, I’ve used <a href="http://uitestingplayground.com/">http://uitestingplayground.com/</a><br>Big thanks to the authors!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a3d067499d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>