<?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 Mike Stop Continues on Medium]]></title>
        <description><![CDATA[Stories by Mike Stop Continues on Medium]]></description>
        <link>https://medium.com/@mikestopcontinues?source=rss-83cb14ea8e7a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*uJXAp1G1unZf2u8e.jpg</url>
            <title>Stories by Mike Stop Continues on Medium</title>
            <link>https://medium.com/@mikestopcontinues?source=rss-83cb14ea8e7a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 00:05:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mikestopcontinues/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[How to Run Snapshot Tests in CI/CD with Playwright]]></title>
            <link>https://medium.com/@mikestopcontinues/how-to-run-snapshot-tests-in-ci-cd-with-playwright-7f78ff6ae4e8?source=rss-83cb14ea8e7a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f78ff6ae4e8</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[user-experience]]></category>
            <category><![CDATA[playwright-test]]></category>
            <category><![CDATA[visual-testing]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Mike Stop Continues]]></dc:creator>
            <pubDate>Thu, 07 Mar 2024 02:02:18 GMT</pubDate>
            <atom:updated>2024-03-07T02:02:18.011Z</atom:updated>
            <content:encoded><![CDATA[<p>Visual tests are a powerful tool, but they’re hell to work with in CI/CD. They’re slow, flaky, a pain to debug, and difficult to maintain.</p><p>Getting them going is no easy task. After all, you need some way to store the snapshots between runs, and you need some way to let your pipeline know when it’s OK to update the snapshot cache.</p><p>Thankfully, I took care of all this for you. :)</p><p>This article solves all of these problems, and lays the foundation for you to take your visual tests to the next level.</p><p>If you get value here, you’ll love my <a href="https://www.browsercat.com/post/ultimate-guide-visual-testing-playwright">Ultimate Guide to Visual Testing in Playwright</a>. It covers advanced testing techniques, fine-tuning your snapshot configuration, and more.</p><p>Let’s get started…</p><h3>1. Configure Playwright for CI/CD</h3><p>Your CI/CD environment is not like your local environment, and we should account for that in our Playwright configuration.</p><p>Update your `playwright.config.ts` with the following options. Feel free to merge these with any other options you’ve set so far:</p><pre>import {defineConfig, devices} from &#39;@playwright/test&#39;;<br><br>const isCI = !!process.env.CI;<br><br>export default defineConfig({<br>  timeout: 1000 * 60,<br>  workers: isCI ? 1 : &#39;50%&#39;,<br>  retries: isCI ? 2 : 0,<br>  forbidOnly: isCI,<br><br>  outputDir: &#39;.test/spec/output&#39;,<br>  snapshotPathTemplate: &#39;.test/spec/snaps/{projectName}/{testFilePath}/{arg}{ext}&#39;,<br>  testMatch: &#39;*.spec.{ts,tsx}&#39;,<br><br>  reporter: [<br>    [&#39;html&#39;, {<br>      outputFolder: &#39;.test/spec/results&#39;, <br>      open: &#39;never&#39;,<br>    }],<br>    isCI ? [&#39;github&#39;] : [&#39;line&#39;],<br>  ],<br>});</pre><p>Here’s what’s going on:</p><ul><li>The top few options account for the limited resources available in a CI environment. Tests will run slower, and they’ll be a little more flaky, so we need to adapt accordingly.</li><li>The next batch of options organize all of your tests’ outputs into the `.test` directory. This will make it easy to cache. Add `.test/` to your `.gitignore` file. None of this stuff should be committed to your repo.</li><li>Lastly, we’re going to generate `html` and `github` reports in CI/CD. The `html` report will be useful for debugging, and the `github` report will be useful for reviewing results with minimal output.</li></ul><h3>2. Run your tests in CI/CD</h3><p>Next, let’s create a basic pipeline. It doesn’t do everything (yet), but it’s a solid foundation to work from.</p><p>Create a file at `.github/workflows/visual-tests.yml`:</p><pre>name: Visual Tests<br><br>on:<br>  push:<br>    branches:<br>      - &quot;*&quot;<br><br>  pull_request:<br>    branches:<br>      - &quot;*&quot;<br><br>jobs:<br>  run-tests:<br>    runs-on: ubuntu-latest<br>    timeout-minutes: 15<br>    steps:<br>      - name: Checkout<br>        uses: actions/checkout@v4<br><br>      - name: Set up Node<br>        uses: actions/setup-node@v3<br>        with:<br>          cache: pnpm<br>          node-version-file: .nvmrc<br>          check-latest: true<br><br>      - name: Install deps<br>        run: |<br>          npm install<br>          npx playwright install<br><br>      - name: Test<br>        run: npx playwright test --ignore-snapshots</pre><p>Notice that we’re running our tests with the ` — ignore-snapshots` flag. Since we have no way to store snapshots between test runs, this is literally the only way to get our tests to pass.</p><p>If you push your repo to Github now, this workflow will run, and it will pass, but it won’t guarantee anything about your app.</p><p>Let’s remedy that…</p><h3>3. Store snapshots between runs</h3><p>For our visual tests to work, we’ll need to store snapshots between runs. For this, we’ll cache them using Github’s “artifacts” feature.</p><p>Second, let’s also write a step that generates new snapshots if they don’t exist. This will solve the problem of our tests failing the first time they run on a branch.</p><p>Third, let’s stop ignoring our snapshot assertions.</p><p>Here’s the updates:</p><pre>      - name: Install deps<br>        run: |<br>          npm install<br>          npx playwright install<br><br>      - name: Set up cache<br>        id: cache<br>        uses: actions/cache@v4<br>        with:<br>          key: cache/${{github.repository}}/${{github.ref}}<br>          restore-keys: cache/${{github.repository}}/refs/heads/master<br>          path: .test/**<br><br>      - name: Initialize snapshots<br>        if: ${{steps.cache.outputs.cache-hit != &#39;true&#39;}}<br>        run: npx playwright test --update-snapshots<br><br>      - name: Test<br>        run: npx playwright test</pre><p>Notice that our cache key includes the current branch as well as a fallback to the `master` branch. That way a new branch has some material to work from on the first push.</p><p>If you trigger the pipeline now, on the first run, you’ll see snapshots generated, the tests pass, and the cache updated. On subsequent runs, you’ll see the cache hit, no new snapshots generated, and the tests still pass.</p><p>Not bad, but what happens when the snapshots need to be updated?</p><h3>4. Trigger a snapshot update</h3><p>Now that we have visual tests that really work, let’s change our workflow so that we can update snapshots on demand.</p><p>First, let’s parameterize our workflow…</p><pre>on:<br>  push:<br>    branches:<br>      - &quot;*&quot;<br><br>  pull_request:<br>    branches:<br>      - &quot;*&quot;<br><br>  # Allow updating snapshots during manual runs<br>  workflow_call:<br>    inputs:<br>      update-snapshots:<br>        description: &quot;Update snapshots?&quot;<br>        type: boolean<br>  <br>  # Allow updating snapshots during automatic runs<br>  workflow_dispatch: <br>    inputs:<br>      update-snapshots:<br>        description: &quot;Update snapshots?&quot;<br>        type: boolean</pre><p>`workflow_call` allows us to manually trigger the workflow with or without updating snapshots. `workflow_dispatch` allows other Github workflows the same set of options.</p><p>Here’s what the manual widget looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*JJOgl70b41r3oe14oMyRgQ.png" /><figcaption>Manually trigger Github workflow</figcaption></figure><p>Let’s also update “Initialize snapshots” to trigger an update when this parameter is enabled:</p><pre>      - name: Initialize snapshots<br>        if: ${{steps.cache.outputs.cache-hit != &#39;true&#39; || inputs.update-snapshots == &#39;true&#39;}}<br>        run: npx playwright test --update-snapshots --reporter html</pre><p>Lastly, let’s upload our HTML report as an artifact, so that we can reference it before deciding if we should ask the workflow to update snapshots… or if we need to debug the problem:</p><pre>      - name: Test<br>        continue-on-error: true<br>        run: npx playwright test<br><br>      - name: Upload test report<br>        if: always()<br>        uses: actions/upload-artifact@v4<br>        with:<br>          name: playwright-report<br>          path: .test/spec/results/<br>          retention-days: 30<br>          overwrite: true</pre><p>Notice that our “Test” step now enables `continue-on-error`, so that we can upload our report even if the tests fail.</p><p>The new “Upload test report” step uploads the report as an artifact. In the workflow results, you’ll see a direct link to a zip file containing our report.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MedQdyqOgiClvO8jhE88Gw.png" /><figcaption>HTML report ready to download</figcaption></figure><h3>5. Speed up your CI/CD pipeline… a lot!</h3><p>Things are going great, but there’s one more thing we can do to make visual tests even better: <em>make them blazingly fast!</em></p><p>You’ve probably noticed two steps are slowing your pipeline down:</p><p>1. Installing Playwright browsers.</p><p>2. Running tests serially.</p><p>Thankfully, we can fix both of these issues, and most-likely for free!</p><p><a href="https://www.browsercat.com/hosted-playwright">BrowserCat</a> hosts a fleet of Playwright browsers in the cloud that you can connect to with just a few lines of code.</p><p>If you do so, you won’t have to install browsers in your CI/CD environment, and you’ll be able to run your tests entirely in parallel.</p><p>And the best part? BrowserCat has an <em>awesome</em> forever-free plan. Unless you’re running a huge team, you’ll probably never have to pay a dime.</p><p>So let’s get started!</p><p>First, sign up for a free account at <a href="https://app.browsercat.com/">BrowserCat</a>.</p><p>Second, create an <a href="https://app.browsercat.com/keys">API key</a> and store it as a secret named `BROWSERCAT_API_KEY` in your Github repository. You can do this by navigating to your repository, clicking “Settings,” then “Secrets,” then “Actions,” then “New repository secret.”</p><p>Third, let’s update `playwright.config.ts` to use BrowserCat:</p><pre>const isCI = !!process.env.CI;<br>const useBC = !!process.env.BROWSERCAT_API_KEY;<br><br>export default defineConfig({<br>  timeout: 1000 * 60,<br>  workers: useBC ? 10 : isCI ? 1 : &#39;50%&#39;,<br>  retries: useBC || isCI ? 2 : 0,<br>  maxFailures: useBC &amp;&amp; !isCI ? 0 : 3,<br>  forbidOnly: isCI,<br><br>  use: {<br>    connectOptions: useBC ? {<br>      wsEndpoint: &#39;wss://api.browsercat.com/connect&#39;,<br>      headers: {&#39;Api-Key&#39;: process.env.BROWSERCAT_API_KEY},<br>    },<br>  },<br>});</pre><p>In the updates above, you’ll notice we’ve increased parallelization to 10 workers when using BrowserCat. This is a good starting point, but you can increase it significantly more without issue.</p><p>Notice that this config connects to BrowserCat whenever `BROWSERCAT_API_KEY` is defined. This is useful for running tests locally, as well as in CI/CD.</p><p>OK, now here’s the last bit of magic… Let’s stop installing Playwright’s browsers every time we run our pipeline:</p><pre>      - name: Install deps<br>        run: npm install</pre><p>If you run your pipeline now, you’ll witness a dramatic speed-up, even with just a single test in your suite. And with 1000 free credits per month, you can run your pipeline for hours on end with plenty of time left over.</p><h3>Next Steps…</h3><p>You’ve got your CI/CD pipeline working. Now it’s time to write some tests!</p><p>Be sure to check out my <a href="https://www.browsercat.com/post/ultimate-guide-visual-testing-playwright">Ultimate Guide to Visual Testing in Playwright</a> for advanced snapshot testing strategies and ready-made solutions for running visual tests in CI/CD.</p><p>In the meantime, happy testing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f78ff6ae4e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Configuring Snapshot Tests in Playwright]]></title>
            <link>https://medium.com/@mikestopcontinues/configuring-snapshot-tests-in-playwright-8afec5cb4302?source=rss-83cb14ea8e7a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8afec5cb4302</guid>
            <category><![CDATA[playwright-test]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[visual-testing]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Mike Stop Continues]]></dc:creator>
            <pubDate>Wed, 06 Mar 2024 01:52:08 GMT</pubDate>
            <atom:updated>2024-03-06T01:52:08.023Z</atom:updated>
            <content:encoded><![CDATA[<p>Playwright’s snapshot tests are incredibly powerful, but they can be very flaky without the right configuration.</p><p>By the end of this article, you’ll have a solid understanding of how to configure your visual tests for the perfect balance of stability, security, and validity.</p><p>If you’re interested in going deeper into visual testing, you’ll love my <a href="https://www.browsercat.com/post/ultimate-guide-visual-testing-playwright">Ultimate Guide to Visual Testing in Playwright</a>. It covers advanced testing techniques, CI/CD integration, and more.</p><p>Let’s get started…</p><h3>Custom Snapshot File Names</h3><p>Playwright automatically names your snapshots based on the name of the test. If you’re only using snapshots for visual testing, that’s fine.</p><p>However, many users like to repurpose these images for documentation, style guides, and deployment reports. These tasks demand consistent file names.</p><p>Name your snapshots like so:</p><pre>test(&#39;custom snapshot names&#39;, async ({page}) =&gt; {<br>  await page.goto(&#39;https://www.browsercat.com&#39;);<br>  const $hero = page.locator(&#39;main &gt; header&#39;);<br><br>  await expect(page).toHaveScreenshot(&#39;home-page.png&#39;);<br>  await expect($hero).toHaveScreenshot(&#39;home-hero.png&#39;);<br><br>  const $footer = page.locator(&#39;body &gt; footer&#39;);<br>  const footImg = await $footer.screenshot();<br><br>  expect(footImg).toMatchSnapshot(&#39;home-foot.png&#39;)<br>});</pre><p>Note: Custom snapshot names don’t completely control the file name unless you also configure custom directories. With the default configuration, Playwright adds a suffix to your file names to ensure they’re unique across projects.</p><p>Read on for how to customize the snapshot directory structure…</p><h3>Custom Snapshot Directories</h3><p>By default, Playwright stores snapshots in the same directory as the test file that created them. This method has numerous shortcomings:</p><ul><li>It makes navigating your codebase more difficult.</li><li>It’s hard to exclude snapshots from version control.</li><li>It’s not easy to cache results between CI/CD runs.</li><li>And it gets in the way of custom snapshot file names.</li></ul><p>So let’s tell Playwright to store our snapshots in a custom directory. Update your `playwright.config.ts`:</p><pre>export default defineConfig({<br>  snapshotPathTemplate: &#39;.test/snaps/{projectName}/{testFilePath}/{arg}{ext}&#39;,<br><br>  // etc.<br>});</pre><p>With the above configuration, if our test file is stored at `./tests/homepage.spec.ts`, the Playwright will store our snapshots like so:</p><pre>.test/<br>  snaps/<br>    tests/<br>      homepage.spec.ts/<br>        home-page.png<br>        home-hero.png<br>        home-foot.png</pre><p>With this pattern, you can exclude your snapshots from version control, you can cache your results in CI/CD, and you can easily review failed tests as they arise.</p><p>Read more about the your options in the Playwright docs for <a href="https://playwright.dev/docs/api/class-testconfig#test-config-snapshot-path-template">snapshot path templates</a>.</p><h3>Make Visual Tests More Forgiving</h3><p>Out of the box, visual tests are very strict. If a single pixel fails, your test fails. Thankfully, Playwright provides numerous controls for tuning how sensitive your visual tests should be.</p><p>Here are your options:</p><ul><li>`threshold`: How much must a single pixel vary for it to be considered _different_. Values are a percentage from `0` to `1`, with `0.2` as the default.</li><li>`maxDiffPixels`: The maximum number of pixels that can differ while still passing the test. By default, this option is disabled.</li><li>`maxDiffPixelRatio`: The maximum percentage of pixels that can differ while still passing the test. Values are a percentage from `0` to `1`, but this control is disabled by default.</li></ul><p>You can tune these options globally or per-assertion.</p><h4>Configure forgiveness globally</h4><p>To configure your snapshot options globally, update your `playwright.config.ts`:</p><pre>export default defineConfig({<br>  expect: {<br>    toHaveScreenshot: {<br>      threshold: 0.25,<br>      maxDiffPixelRatio: 0.025,<br>      maxDiffPixels: 25,<br>    },<br>    toMatchSnapshot: {<br>      threshold: 0.25,<br>      maxDiffPixelRatio: 0.025,<br>      maxDiffPixels: 25,<br>    }<br>  },<br>});</pre><h4>Override forgiveness per-assertion</h4><p>To override your global snapshot options, update your test file:</p><pre>test(&#39;forgiving snapshots&#39;, async ({page}) =&gt; {<br>  await page.goto(&#39;https://www.browsercat.com&#39;);<br>  const $hero = page.locator(&#39;main &gt; header&#39;);<br><br>  await expect(page).toHaveScreenshot({<br>    maxDiffPixelRatio: 0.15,<br>  });<br><br>  await expect($hero).toHaveScreenshot({<br>    maxDiffPixels: 100,<br>  });<br>});</pre><h4>How do I tune these options?</h4><p>To converge on the correct setting for your app, review the failing “diff” images produced by your tests. In those images, yellow pixels indicate pixels that are within the `threshold` allowance, while red pixels fail the test.</p><p>First try to increase `threshold`, and see if you can gobble up the red pixels in your snapshots. But be careful: a high `threshold` will cause false negatives. I wouldn’t go any higher than `0.35`, and that’s high.</p><p>If `threshold` doesn’t work, focus on `maxDiffPixelRatio` and `maxDiffPixels`. And consider the trade-offs these options entail.</p><p>Since `maxDiffPixelRatio` is relative to image size, it’s more likely to yeild good results across a wide range of images. This makes it a good contender for a global setting… but only if you set it conservatively! After all, 10% of a full page image will allow a lot of variation.</p><p>On the other hand, since `maxDiffPixels` is a constant value, it gives you much better control on individual tests. But it’s also much more risky if applied globally, even at a low setting. For small images, a high `maxDiffPixels` might constitute a huge percentage of the image.</p><h3>Next Steps…</h3><p>That’s really all there is to configuring your visual tests, but there’s so much more to learn. For advance snapshot testing strategies and ready-made solution for running visual tests in CI/CD, check out my <a href="https://www.browsercat.com/post/ultimate-guide-visual-testing-playwright">Ultimate Guide to Visual Testing in Playwright</a>.</p><p>In the meantime, happy testing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8afec5cb4302" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Snapshot Testing in Playwright]]></title>
            <link>https://medium.com/@mikestopcontinues/advanced-snapshot-testing-in-playwright-109195201869?source=rss-83cb14ea8e7a------2</link>
            <guid isPermaLink="false">https://medium.com/p/109195201869</guid>
            <category><![CDATA[user-experience]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[playwright-test]]></category>
            <dc:creator><![CDATA[Mike Stop Continues]]></dc:creator>
            <pubDate>Tue, 05 Mar 2024 01:47:37 GMT</pubDate>
            <atom:updated>2024-03-05T01:47:37.747Z</atom:updated>
            <content:encoded><![CDATA[<p>Playwright’s snapshot assertions are an incredibly powerful tool for ensuring your app’s UI remains consistent across code changes, browsers, and devices. But they’re not always easy to use.</p><p>This article dives deep on snapshot testing in Playwright, covering a wide range of features and techniques. By the end, you’ll be a snapshot testing master, ensuring your app’s flawless visual consistency across browsers and devices.</p><p>When you’re finished, check out my <a href="https://www.browsercat.com/post/ultimate-guide-visual-testing-playwright">Ultimate Guide to Visual Testing with Playwright</a>. It covers setup, advanced configuration, and running your visual tests in CI/CD.</p><p>Let’s go!</p><h3>Page vs. Element Snapshots</h3><p>Playwright’s visual testing API allows you to take snapshots of the entire page or just a specific element.</p><p>But when is the right time to use one over the other?</p><h4>When should I use page snapshots?</h4><p>Page snapshots are excellent for verifying the entire page works as expected. Use page snapshots to test layout, responsiveness, and accessibility.</p><p>But be warned: Page snapshots can be flaky. After all, if anything within the viewport changes, the entire snapshot will fail. We’ll cover strategies for minimizing these effects later, but for now, it’s wise to consider page snapshots a powerful, blunt instrument.</p><p>You’ve already seen a page snapshot in action. Here’s a refresher:</p><pre>test(&#39;page snapshot&#39;, async ({page}) =&gt; {<br>  await page.goto(&#39;https://www.browsercat.com&#39;);<br>  await expect(page).toHaveScreenshot();<br>});</pre><h4>When should I use element snapshots?</h4><p>Element snapshots, as you expect, focus exclusively on a single page element. This makes them an excellent choice for testing components in isolation, or for verifying an element behaves as expected within a certain context.</p><p>Element snapshots are substantially less brittle than page snapshots, but they require a bit more overhead to set up. After all, their narrow targeting means you need more of them to cover the same surface area as a page snapshot.</p><p>Here’s an example of an element snapshot:</p><pre>test(&#39;element snapshot&#39;, async ({page}) =&gt; {<br>  await page.goto(&#39;https://www.browsercat.com&#39;);<br>  const $button = page.locator(&#39;button&#39;).first();<br>  await expect($button).toHaveScreenshot();<br>});</pre><h3>Working with Page Snapshots</h3><p>Let’s explore some useful features and common use-cases for page snapshots…</p><h4>Cropping Page Snapshots</h4><p>Sometimes the entire viewport isn’t necessary to prove your test passes. And sometimes a portion of the viewport changes frequently by design, turning an otherwise great test into a flake.</p><p>In these cases, it’s best to crop your snapshot to the area of interest. Here’s an example:</p><pre>test(&#39;cropped snapshot&#39;, async ({page}) =&gt; {<br>  await page.goto(&#39;https://www.browsercat.com&#39;);<br>  const {width, height} = page.viewportSize();<br><br>  await expect(page).toHaveScreenshot({<br>    // square at the center of the page<br>    clip: {<br>      x: (width - 400) / 2, <br>      y: (height - 400) / 2, <br>      width: 400, <br>      height: 400,<br>    },<br>  });<br><br>  await expect(page).toHaveScreenshot({<br>    // top slice, maximum possible width<br>    clip: {x: 0, y: 0, width: Infinity, height: 16},<br>  });<br>});</pre><h4>Snapshot the Entire Page</h4><p>By default, Playwright takes a snapshot of the current viewport. This is typically what you want, as the larger the snapshot is, the more likely it is for your test to fail.</p><p>However, full page snapshots have their place. For example, if you’re testing that a page looks the same across different browsers, the the easiest solution is to snapshot the entire page. And since for this kind of test, you aren’t storing the snapshot from previous runs, you’re not going to end up with an overly flaky test.</p><p>Here’s how you take a full page snapshot:</p><pre>test(&#39;full page snapshot&#39;, async ({page}) =&gt; {<br>  await page.goto(&#39;https://www.browsercat.com&#39;);<br>  await expect(page).toHaveScreenshot({<br>    fullPage: true,<br>  });<br>});</pre><h4>Scroll Before Taking a Page Snapshot</h4><p>When working with page snapshots, you’ll often want to scroll the page before the visual assertion.</p><p>Here’s how:</p><pre>test(&#39;scroll before snapshot&#39;, async ({page}) =&gt; {<br>  await page.goto(&#39;https://www.browsercat.com&#39;);<br><br>  await page.evaluate(() =&gt; {<br>    document<br>      .querySelector(&#39;#your-element&#39;)<br>      ?.scrollIntoView({behavior: &#39;instant&#39;});<br>  });<br><br>  await expect(page).toHaveScreenshot();<br>});</pre><p>Note: While Playwright has a `.scrollIntoViewIfNeeded()` method, it will not scroll the element to the top of the viewport. So I recommend the solution above. It will make full use of your viewport and ensure your snapshot is consistent between runs.</p><h3>Working with Element Snapshots</h3><p>Element snapshots are much more “in the weeds” than page snapshots. They bring a lot of power and flexibility.</p><p>Let’s explore some examples…</p><h4>Test Element Interactivity</h4><p>As your component library grows, it becomes harder and harder to keep track of every state of every element in your library.</p><p>In the following example, we snapshot a form input across various states:</p><pre>test(&#39;element states&#39;, async ({page}) =&gt; {<br>  await page.goto(&#39;https://www.browsercat.com/contact&#39;);<br>  const $textarea = page.locator(&#39;textarea&#39;).first();<br><br>  await expect($textarea).toHaveScreenshot();<br>  await $textarea.hover();<br>  await expect($textarea).toHaveScreenshot();<br>  await $textarea.focus();<br>  await expect($textarea).toHaveScreenshot();<br>  await $textarea.fill(&#39;Hey, cool cat!&#39;);<br>  await expect($textarea).toHaveScreenshot();<br>});</pre><h4>Test Element Responsiveness</h4><p>When working with responsive designs, it’s important to ensure your elements look good across the full range of screen sizes.</p><p>Use element snapshots to ensure your components look good at various breakpoints.</p><pre>test(&#39;element responsiveness&#39;, async ({page}) =&gt; {<br>  const viewportWidths = [960, 760, 480];<br>  await page.goto(&#39;https://www.browsercat.com/blog&#39;);<br>  const $post = page.locator(&#39;main article&#39;).first();<br><br>  for (const width of viewportWidths) {<br>    await page.setViewportSize({width, height: 800});<br>    await expect($post).toHaveScreenshot(`post-${width}.png`);<br>  }<br>});</pre><h3>Advanced Snapshot Techniques</h3><p>Page and element snapshots share many common configuration options. Let’s explore the most useful among them…</p><h4>Masking Portions of a Snapshot</h4><p>Sometimes, you’ll want to exclude certain portions of a snapshot. A sub-element or sub-region may change frequently, contain sensitive information, or be irrelevant to the test. For example, a timestamp, an animation, a user email address, or a rotating ad.</p><p>Playwright provides the ability to “mask” these areas, replacing them with a consistent bright color unlikely to be confused for the content of your site.</p><p>Here’s an example:</p><pre>test(&#39;masked snapshots&#39;, async ({page}) =&gt; {<br>  await page.goto(&#39;https://www.browsercat.com&#39;);<br>  const $hero = page.locator(&#39;main &gt; header&#39;);<br>  const $footer = page.locator(&#39;body &gt; footer&#39;);<br><br>  await expect(page).toHaveScreenshot({<br>    mask: [<br>      $hero.locator(&#39;img[src$=&quot;.svg&quot;]&#39;),<br>      $hero.locator(&#39;a[target=&quot;_blank&quot;]&#39;),<br>    ],<br>  });<br>  <br>  await expect($footer).toHaveScreenshot({<br>    mask: [<br>      $footer.locator(&#39;svg&#39;),<br>    ],<br>  });<br>});</pre><p>And here’s what the first masked snapshot looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XPVWpfeMITXY_G-D25DEWg.png" /><figcaption>Masked snapshot image</figcaption></figure><h4>Keeping Styles Constant During Snapshots</h4><p>Visual tests are valuable because they catch unexpected changes to your app’s appearance. Some page elements are too unreliable to include as-is.</p><p>Thankfully, we can include some basic CSS for the duration of a snapshot that restrains or hides troublesome elements from the page.</p><p>Here’s how:</p><pre>test(&#39;consistent styles&#39;, async ({page}) =&gt; {<br>  await page.goto(&#39;https://www.browsercat.com&#39;);<br>  const $hero = page.locator(&#39;main &gt; header&#39;);<br><br>  await expect(page).toHaveScreenshot({<br>    stylePath: [<br>      &#39;./hide-dynamic-elements.css&#39;,<br>      &#39;./disable-scroll-animations.css&#39;,<br>    ],<br>  });<br>  <br>  await expect($hero).toHaveScreenshot({<br>    stylePath: [<br>      &#39;./hide-dynamic-elements.css&#39;,<br>      &#39;./disable-scroll-animations.css&#39;,<br>    ],<br>  });<br>});</pre><h4>Auto-Retry Flaky Snapshots</h4><p>When working with animations or dynamic content, your visual tests can become flaky. Large page snapshots are particularly susceptible.</p><p>Playwright can automatically retry failed visual tests for a certain duration, until it finds a valid match. Enable the feature like so:</p><pre>test(&#39;retry snapshots&#39;, async ({page}) =&gt; {<br>  await page.goto(&#39;https://www.browsercat.com&#39;);<br>  const $hero = page.locator(&#39;main &gt; header&#39;);<br><br>  await expect(page).toHaveScreenshot({<br>    // retry snapshot until timeout is reached<br>    timeout: 1000 * 60,<br>  });<br><br>  await expect($hero).toHaveScreenshot({<br>    // retry snapshot until timeout is reached<br>    timeout: 1000 * 60,<br>  });<br>});</pre><h4>Visual Tests for Generated Images</h4><p>99.9% of the time, page and element snapshots will cover your use-case. But there are times when you’ll want to assert an arbitrary image is consistent across test runs.</p><p>For example, perhaps your application generates QR codes or social share cards. Or perhaps you compress and transform user-uploaded avatars. You’ll want to ensure this functionality doesn’t break.</p><p>Use `expect().toMatchSnapshot()` for this:</p><pre>import {test, expect} from &#39;@playwright/test&#39;;<br>import {buffer} from &#39;stream/consumers&#39;;<br><br>test(&#39;arbitrary snapshot&#39;, async ({page}) =&gt; {<br>  // generates custom avatars — fun!<br>  await page.goto(&#39;https://getavataaars.com&#39;);<br>  await page.locator(&#39;main form button&#39;).first().click();<br><br>  // download the avatar<br>  const avatar = await page.waitForEvent(&#39;download&#39;)<br>    .then((dl) =&gt; dl.createReadStream())<br>    .then((stream) =&gt; buffer(stream));<br><br>  expect(avatar).toMatchSnapshot(&#39;avatar.png&#39;);<br>});</pre><h4>Compare Snapshots Across Browsers</h4><p>All of the tests we’ve written thus far compares the state of your app before and after code changes. But what if you want to compare the state of your app across different browsers and devices?</p><p>To accomplish this, we’re going to lean on Playwright’s “projects” functionality. Projects allow you to define custom test suites with unique configuration. In a mature codebase, you may have quite a lot of these for different devices, environments, and testing strategies.</p><p>Let’s make some magic!</p><p>First, update your `playwright.config.ts`. If you don’t have one yet, create it at the root of your project:</p><pre>const crossBrowserConfig = {<br>  testDir: &#39;./tests/cross-browser&#39;,<br>  snapshotPathTemplate: &#39;.test/cross/{testFilePath}/{arg}{ext}&#39;,<br>  expect: {<br>    toHaveScreenshot: {maxDiffPixelRatio: 0.1},<br>  },<br>};<br><br>export default defineConfig({<br>  // other config here...<br><br>  projects: [<br>    {<br>      name: &#39;cross-chromium&#39;,<br>      use: {...devices[&#39;Desktop Chrome&#39;]},<br>      ...crossBrowserConfig,<br>    },<br>    {<br>      name: &#39;cross-firefox&#39;,<br>      use: {...devices[&#39;Desktop Firefox&#39;]},<br>      dependencies: [&#39;cross-chromium&#39;],<br>      ...crossBrowserConfig,<br>    },<br>    {<br>      name: &#39;cross-browser&#39;,<br>      use: {...devices[&#39;Desktop Safari&#39;]},<br>      dependencies: [&#39;cross-firefox&#39;],<br>      ...crossBrowserConfig,<br>    },<br>  ],<br>});</pre><p>Notice how we’re specifically configuring the `snapshotPathTemplate` to store the snapshots for _all_ browsers in the _same_ location. This will ensure that each test compares its snapshots to the same source images.</p><p>Next, create a new test file at `./tests/cross-browser/homepage.spec.ts`:</p><pre>import {test, expect} from &#39;@playwright/test&#39;;<br><br>test(&#39;cross-browser snapshots&#39;, async ({page, }) =&gt; {<br>  await page.goto(&#39;https://www.browsercat.com&#39;);<br>  await page.locator(&#39;:has(&gt; a figure)&#39;)<br>    .evaluate(($el) =&gt; $el.remove());<br><br>  await expect(page).toHaveScreenshot(`home-page.png`, {<br>    fullPage: true,<br>  });<br>});</pre><p>To avoid a fail, let’s initialize our new snapshots:</p><pre>npx playwright test --project cross-browser -u</pre><p>And then let’s run the tests:</p><pre>npx playwright test --project cross-browser</pre><p>Did all of your tests pass? Depending on your environment, they may not have! Different browsers render fonts, colors, and images differently, even when your app is functioning as expected.</p><p>If your tests failed, you may need to tweak the `maxDiffPixelRatio` and `threshold` options for your snapshots. If you want to debug this issue right now, visit my <em>Ultimate Guide to Visual Testing with Playwright</em>, and learn how to <a href="https://www.browsercat.com/post/ultimate-guide-visual-testing-playwright#make-visual-tests-more-forgiving">make visual tests more forgiving</a>.</p><h3>Next Steps…</h3><p>You’re getting pretty good at this! But there’s still more to learn. For advice on fine-tuning your snapshot tests and running visual tests in CI/CD, check out my <a href="https://www.browsercat.com/post/ultimate-guide-visual-testing-playwright">Ultimate Guide to Visual Testing with Playwright</a>.</p><p>In the meantime, happy testing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=109195201869" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Snapshot Tests in Playwright]]></title>
            <link>https://medium.com/@mikestopcontinues/getting-started-with-snapshot-tests-in-playwright-89ebaa9d309c?source=rss-83cb14ea8e7a------2</link>
            <guid isPermaLink="false">https://medium.com/p/89ebaa9d309c</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[playwright-test]]></category>
            <category><![CDATA[user-experience]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Mike Stop Continues]]></dc:creator>
            <pubDate>Mon, 04 Mar 2024 01:37:37 GMT</pubDate>
            <atom:updated>2024-03-04T01:37:37.169Z</atom:updated>
            <content:encoded><![CDATA[<p>As your web app matures, it becomes challenging to ensure your GUI doesn’t break with any given update. There are a lot of browsers and devices, and countless states for every one of your components. Unit tests ensure your code remains consistent, and E2E tests will ensure your system remains consistent, but neither will catch visual anomalies, layout issues, or platform compatibility issues.</p><p>Enter <em>visual testing</em>. Visual tests store snapshots of your app’s appearance, and compares them to the current state of your app. No more surprise bugs. No more developing in three different browsers and 12 different breakpoints. Visual testing automates the process, ensuring your app looks exactly right, all the time.</p><p>This article covers the basics of visual testing with Playwright. If you’re interested in going deeper into visual testing, you’ll love my <a href="https://www.browsercat.com/post/ultimate-guide-visual-testing-playwright">Ultimate Guide to Visual Testing in Playwright</a>.</p><p>Let’s get started…</p><h3>1. Install dependencies</h3><p>If you already have Playwright installed, skip this step.</p><p>Otherwise, install your dependencies and create a sample test file:</p><pre># Install node dependencies<br>npm install -D @playwright/test<br>npm install -D typescript<br><br># Install playwright browsers<br>npx playwright install<br><br># Create the test file<br>mkdir -p tests<br>touch tests/homepage.spec.ts</pre><h3>2. Write your first visual test</h3><p>Open `tests/homepage.spec.ts` and add the following code:</p><pre>import {test, expect} from &#39;@playwright/test&#39;;<br><br>test(&#39;home page visual test&#39;, async ({page}) =&gt; {<br>  await page.goto(&#39;https://www.browsercat.com&#39;);<br>  await expect(page).toHaveScreenshot();<br>});</pre><h3>3. Run your visual tests</h3><p>Run your tests with the following command:</p><pre>npx playwright test</pre><p>The first time your run your tests, they will fail with an error message like this:</p><pre>Error: A snapshot doesn&#39;t exist at {TEST_OUTPUT_PATH}, writing actual.</pre><p>This is expected. Since Playwright has nothing to compare `expect(page).toHaveSnapshot()` to, it _must_ fail the test. But don’t worry: the next time you run your tests, Playwright will compare the current state of the page to the stored snapshot.</p><p>So run your tests a second time:</p><pre>npx playwright test</pre><p>Success! You should see a message like this:</p><pre>Running 1 test using 1 worker<br>  1 passed (6.6s)</pre><p>If your test failed, take a few minutes to see if you can fix the issue. If not, continue reading. I cover numerous troubleshooting tips later in this article.</p><h4>Where are snapshots stored?</h4><p>By default, test snapshots are stored alongside the test file that created them.</p><p>When a visual test fails, Playwright will store the “before” image, the “after” image, and a “diff” image in the `./test-results` directory. These will come in handy later, for debugging your failed tests.</p><p>(Keep reading for advice on configuring the location of these snapshots. You probably don’t want test output littering your codebase.)</p><h3>4. Updating test snapshots</h3><p>Awesome! Your test now confirms there haven’t been any changes to the page, but what if you actually want to make some changes?</p><p>To update your snapshots, run your tests with the ` — update-snapshots` (or `-u`) flag:</p><pre>npx playwright test -u</pre><p>This command will run your tests and update the snapshots to match the current state of the page. If you run this now, you should expect a passing result.</p><p>A word of caution: This command updates _all_ snapshots. Be very careful, as it’s easy to accidentally update snapshots you didn’t intend to.</p><h4>How do I update only _some_ snapshots?</h4><p>To update the snapshots for a subset of tests, we can filter tests from the CLI. Only matching tests will be updated.</p><pre># Update tests with matching file name<br>npx playwright test -u &quot;**/home*.spec.ts&quot;<br><br># Update tests with matching test name<br>npx playwright test -u --grep &quot;home&quot; --grep-invert &quot;zzz&quot;<br><br># Updates tests within project<br>npx playwright test -u --project &quot;chromium&quot;</pre><p>We’ll go deeper into snapshot management later, but for now, let’s focus on debugging…</p><h3>5. Debug visual tests</h3><p>We know how to update failing tests’ snapshots, but what about when a test is failing because of a bug?</p><p>To explore this scenario, let’s update our test so that our snapshot fails:</p><pre>test(&#39;home page visual test&#39;, async ({page}) =&gt; {<br>  await page.goto(&#39;https://www.browsercat.com&#39;);<br>  await expect(page).toHaveScreenshot({<br>    // crop the screenshot to a specific area<br>    clip: {x: 0, y: 0, width: 500, height: 500},<br>  });<br>});</pre><p>Now let’s run the tests, asking playwright to produce an HTML report:</p><pre>npx playwright test --reporter html</pre><p>After that command, your browser should have opened to your test report. And it should show a failed result.</p><p>Scroll down to the bottom of the page, and you’ll see this widget:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bMHfqS5-gxKgpOeB9LCFoA.png" /><figcaption>Visual test diff</figcaption></figure><p>The “Diff” view offers a stark comparison between the expected and actual screenshots. However, I find the “Slider” view to be the most useful for actually fixing issues.</p><h4>How do I interpret the “diff” view?</h4><p>The “diff” view shows the difference between the expected and actual screenshots.</p><p>Yellow pixels vary between snapshots, but they fall within the allowed threshold for differences.</p><p>Red pixels fall outside the allowed threshold for differences. By default, even a single red pixel will fail your test.</p><p>For advice on configuring these thresholds, visit my <em>Ultimate Guide to Visual Testing with Playwright</em>, and learn how to <a href="https://www.browsercat.com/post/ultimate-guide-visual-testing-playwright#make-visual-tests-more-forgiving">make visual tests more forgiving</a>.</p><h4>Do I need to use the HTML report?</h4><p>No, you don’t have to use the HTML report to run visual tests (though I recommend it). Whether you generate an HTML report, failing visual tests will automatically output the “before,” “after,” and “diff” images to the `./test-results` directory.</p><p>Often, I’ll open the “before” image directly in VSCode while I work. That way I can keep my browser focused on my development app.</p><h3>6. Use UI mode for quick visual testing</h3><p>Playwright has an industry-leading “UI Mode” that makes working with tests a breeze.</p><p>While it has numerous killer features, my favorite is that it <em>automatically</em> snapshots the test after <em>every single step</em>. This allows you to quickly debug your tests. It also makes it very easy to spot the right places to insert a visual assertion.</p><p>To run your tests in UI mode, use the following command:</p><pre>npx playwright test --ui</pre><p>I encourage you to explore UI mode, as it has a wealth of useful features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bICjVq7XmZThSYYcqfy2kg.png" /></figure><h3>Next Steps…</h3><p>You’ve now got a solid foundation for visual testing with Playwright. But there’s so much more to learn!</p><p>For advanced tips, configuration guidance, and strategies for managing visual tests in your CI/CD pipeline, check out my <a href="https://www.browsercat.com/post/ultimate-guide-visual-testing-playwright">Ultimate Guide to Visual Testing in Playwright</a>.</p><p>In the meantime, happy testing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89ebaa9d309c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Refactor Playwright Locators Like a Boss]]></title>
            <link>https://medium.com/@mikestopcontinues/refactor-playwright-locators-like-a-boss-65f2003a4450?source=rss-83cb14ea8e7a------2</link>
            <guid isPermaLink="false">https://medium.com/p/65f2003a4450</guid>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[playwright-test]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Mike Stop Continues]]></dc:creator>
            <pubDate>Fri, 22 Dec 2023 12:01:37 GMT</pubDate>
            <atom:updated>2023-12-22T12:01:37.872Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<p>Your first Playwright automations are likely to be a little… messy. After all, the web is a messy place. But taking automations to production means untangling that ball of spaghetti code, and transforming it into something more clear, performant, and maintainable.</p><p>This article explores a few great techniques for refactoring your Playwright locators. And every idea is really quick to implement. After all, there’s no point in suggesting optimizations that make your developer life painful!</p><p>If you find this post helpful, check out my full <a href="https://www.browsercat.com/post/strengthen-selectors-and-locators-in-playwright">Playwright locator deep-dive</a> for even more ideas on optimizing your scripts for speed, scale, and stability.</p><p>Let’s get started!</p><h3>Extend Playwright with Custom Selectors</h3><p>Playwright opens up a world of possibilities with its selector engine, not only by supporting a wide range of built-in selectors but also by empowering users to define their own.</p><p>Custom selectors can be tailored to unique application requirements, make scripts more readable, and support complex selection logic that goes beyond the basics.</p><p>Here are some ideas:</p><ol><li>data-state: Select elements based on a data attribute representing state (e.g., data-state=\&quot;active\&quot;) to target specific UI states in a single-page application.</li><li>closest: Select the closest ancestor of an element that matches a certain selector—akin to the Element.closest() method in JavaScript.</li><li>shadow: Target elements that are within a specific shadow DOM.</li><li>rotation: Select an element rotated within a particular range.</li></ol><p>To demonstrate the potential of custom selectors in Playwright, let’s create the data-state selector described above...</p><pre>import * as pw from &#39;playwright&#39;;<br><br>// register custom selector<br>await pw.selectors.register(&#39;data-state&#39;, () =&gt; ({<br>  query(root: Node, selector: string) {<br>    return root.querySelector(`[data-state=&quot;${selector}&quot;]`);<br>  },<br><br>  queryAll(root: Node, selector: string) {<br>    return Array.from(<br>      root.querySelectorAll(`[data-state=&quot;${selector}&quot;]`)<br>    );<br>  },<br>}));<br><br>const browser = await pw.firefox.launch();<br>const page = await browser.newPage();<br>await page.goto(&#39;https://example.com&#39;);<br><br>// use the custom selector<br>const $active = page.locator(&#39;data-state=active&#39;);<br>await $active.click();</pre><p>As you can see, it takes very little to create a custom selector. Since Playwright grants you access to the underlying DOM, the sky’s the limit.</p><h3>Use the Page Object Model</h3><p>The Page Object Model (POM) is a design pattern widely used in automation for improving maintainability and reducing duplication. A page object encapsulates the behaviors and elements of a specific page in your target site, making it easy to update the code as needed.</p><p>Here’s an example of what a page object might look like for a login page. Notice how it collects common locators as well as behaviors likely to be repeated in multiple different scripts…</p><pre>import {Page} from &#39;playwright&#39;;<br><br>export class LoginPage {<br>  page: Page;<br><br>  constructor(page: Page) {<br>    this.page = page;<br>  }<br><br>  get $usernameInput() {<br>    return this.page.getByLabel(&#39;Username&#39;);<br>  }<br><br>  get $passwordInput() {<br>    return this.page.getByLabel(&#39;Password&#39;);<br>  }<br><br>  get $loginButton() {<br>    return this.page.getByText(&#39;Login&#39;);<br>  }<br><br>  public async login(username: string, password: string) {<br>    await this.$usernameInput.fill(username);<br>    await this.$passwordInput.fill(password);<br>    await this.$loginButton.click();<br>  }<br>}</pre><p>Here’s how you might use the LoginPage POM:</p><pre>import * as pw from &#39;playwright&#39;;<br>import {LoginPage} from &#39;./LoginPage&#39;;<br><br>const browser = await pw.webkit.launch();<br>const page = await browser.newPage();<br>await page.goto(&#39;https://app.browsercat.com/sign-in&#39;);<br><br>const loginPage = new LoginPage(page);<br>await loginPage.login(&#39;user@example.com&#39;, &#39;p1a2s3s4word!&#39;);<br>await loginPage.$loginButton.click();</pre><h3>Compose Page Objects from Components</h3><p>I’ve found you can extend the wisdom of the Page Object Model further. Consider that most websites are built from reusable components that are repeated on multiple pages. Rather than designing POMs from scratch, instead, you can compose them from components found on page after page.</p><p>Here’s how we might leverage component objects for AppMenuBar, ChatWidget, and AppFooter:</p><pre>// Define the separate components<br>class AppMenuBar {<br>  constructor(public page: Page) {}<br>  get $logo () {}<br>  get $menuButton () {}<br>}<br><br>class ChatWidget {<br>  constructor(public page: Page) {}<br>  get $chatToggle () {}<br>  get $messageInput () {}<br>  get $sendButton () {}<br><br>  async sendMessage(message: string) {}<br>}<br><br>class AppFooter {<br>  constructor(public page: Page) {}<br>  get $uptimeStatus () {}<br>}<br><br>// Compose these components into a complete page object<br>class ContactPage {<br>  menuBar: AppMenuBar;<br>  chatWidget: ChatWidget;<br>  footer: AppFooter;<br><br>  constructor(public page: Page) {<br>    this.menuBar = new AppMenuBar(page);<br>    this.chatWidget = new ChatWidget(page);<br>    this.footer = new AppFooter(page);<br>  }<br>}<br><br>// Use the composed POM<br>const browser = await pw.chromium.launch();<br>const page = await browser.newPage();<br>await page.goto(&#39;https://www.browsercat.com/contact&#39;);<br>const contactPage = new ContactPage(page);<br><br>// Use the component methods<br>await contactPage.menuBar.$menuButton.click();<br>await contactPage.chatWidget.sendMessage(&#39;Hello there!&#39;);</pre><p>In the example above, the composed ContactPage object becomes a powerful and convenient abstraction, bundling the interactions for the menu bar, chat widget, and app footer, which are then used in repeated interactions. This approach keeps your scripts DRY (Don&#39;t Repeat Yourself) and makes it easy to update component interactions when the UI changes, without having to change each usage.</p><h3>Next steps</h3><p>As you can see, these techniques are quick to implement and can have a big impact on the readability, maintainability, and performance of your Playwright scripts. Give one or two a try on an existing project, and see how it goes!</p><p>Experimentation is the best way to learn.</p><p>If you’re looking for more ideas on how to strengthen your Playwright scripts, check out my <a href="https://www.browsercat.com/post/strengthen-selectors-and-locators-in-playwright">locator deep-dive</a> next.</p><p>Happy automating!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65f2003a4450" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handle Errors and Fallbacks in Playwright]]></title>
            <link>https://medium.com/@mikestopcontinues/handle-errors-and-fallbacks-in-playwright-4757292a5dc9?source=rss-83cb14ea8e7a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4757292a5dc9</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[playwright-test]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-scraping]]></category>
            <dc:creator><![CDATA[Mike Stop Continues]]></dc:creator>
            <pubDate>Thu, 21 Dec 2023 12:01:27 GMT</pubDate>
            <atom:updated>2023-12-21T12:01:27.721Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<p>All robust automations share one thing in common: they can handle the tides of uncertainty the web throws at them day after day. When developing robust applications on top of Playwright scripts, managing the unexpected is key to winning the day.</p><p>This article explores some practical strategies for building resilience into Playwright scripts, ensuring they can handle errors, adapt to varied content, and provide clear control flow.</p><p>By the way, if you find this article helpful, check out my complete <a href="https://www.browsercat.com/post/strengthen-selectors-and-locators-in-playwright">Playwright locator deep-dive</a> for a detailed look at optimizing your locators for speed, scale, and stability.</p><p>Let’s get started!</p><h3>Try Multiple Locator Strategies</h3><p>When scraping web pages, you may encounter variability in where and how data is presented. For instance, retrieving a star rating from a product page can be challenging because the value could be in a metadata field, within the text of an element, or even graphically represented with icons.</p><pre>const maybeRatings = await Promise.all([<br>  page.locator(&#39;.rating-value&#39;).textContent(),<br>  page.locator(&#39;.star-rating img.star&#39;).count(),<br>  page.locator(&#39;meta[name=&quot;description&quot;]&#39;)<br>    .getAttribute(&#39;content&#39;)<br>    .then((str) =&gt; (/\n\.\n+ stars/u).exec(str ?? &#39;&#39;)?.[0]),<br>]);<br><br>const bestRating = maybeRatings.reduce((pick, rating) =&gt; {<br>  return pick ?? parseFloat(rating) || null;<br>}, null);</pre><p>In this example, the script attempts multiple strategies to capture the rating, testing each result to ensure it looks like an actual rating number.</p><h3>Quietly Skip Optional Content</h3><p>Not all content is essential for the successful completion of a script. For example, let’s say you wanted to scrape a book product page, but you can’t always guarantee the page count is available. In this case, you’d only want the script to fail if critical values (like the book title) weren’t found, but to pass otherwise.</p><pre>const title = await page.locator(&#39;.book-title&#39;)<br>  .textContent();<br>const author = await page.locator(&#39;.author-name&#39;)<br>  .textContent();<br>const pageCount = await page.locator(&#39;.page-count&#39;)<br>  .textContent();<br><br>const details = {<br>  title, <br>  author,<br>  pageCount: parseInt(pageCount) || null,<br>};<br><br>assert(!!details.title &amp;&amp; !!details.author);</pre><p>The function demonstrates the selective inclusion of optional data. If present, it enriches the results. But if absent, it doesn’t constitute failure.</p><h3>Clarify Your Control Flow</h3><p>Control flow can become unclear if scripts are peppered with conditional statements and error handling. Playwright’s locators can help us streamline the process.</p><p>In the following example, we only interact with the table of contents if it exists.</p><pre>const $toc = page.locator(&#39;aside.contents&#39;);<br><br>if (await $toc.count() &gt; 0) {<br>  const $lastLink = await $toc.locator(&#39;a&#39;).last();<br>  await $lastLink.click();<br><br>  const depth = await page.evaluate(() =&gt; window.scrollY);<br>  console.log(`Scrolled to depth: ${depth}`);<br>} else {<br>  console.log(&#39;No table of contents found.&#39;);<br>}</pre><p>This example demonstrates a clear control flow where the presence of a table of contents triggers conditional behavior, but doesn’t result in an error otherwise.</p><h3>Retry Failed Gestures</h3><p>In some scenarios, you might want a script to retry an action until a certain condition is met, like rolling a digital die until a specific number appears.</p><pre>const $d20 = page.getByRole(&#39;button&#39;, {name: &#39;Roll d20&#39;});<br>const $result = page.locator(&#39;#d20-result&#39;);<br><br>page.waitForFunction(async () =&gt; {<br>  await $d20.click();<br>  const roll = await $result.textContent().then((str) =&gt; parseInt(str));<br><br>  return roll === 20;<br>});</pre><p>This code snippet rolls a virtual die, retrying the gesture until the desired outcome is achieved, showcasing a controlled and persistent interaction pattern.</p><p>As you can see, these strategies equip your web automation tasks with accuracy and fault tolerance, ensuring smooth interaction with a variety of web pages, content structures, and unexpected circumstances.</p><h3>Next steps</h3><p>Now that you’ve got some new tools in your belt, review your most recent automations and see if you can apply any of these strategies to improve their resilience.</p><p>I find the key to making my scripts production-ready is going line-by-line looking for potential failure modes and workarounds. It’s a tedious process, but it pays off in the long run.</p><p>Remember, check out my complete <a href="https://www.browsercat.com/post/strengthen-selectors-and-locators-in-playwright">Playwright locator deep-dive</a> for a detailed look at optimizing your locators for speed, scale, and stability.</p><p>Happy automating!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4757292a5dc9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Manage Delays and Async in Playwright]]></title>
            <link>https://medium.com/@mikestopcontinues/manage-delays-and-async-in-playwright-616663f62043?source=rss-83cb14ea8e7a------2</link>
            <guid isPermaLink="false">https://medium.com/p/616663f62043</guid>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[playwright-test]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Mike Stop Continues]]></dc:creator>
            <pubDate>Wed, 20 Dec 2023 12:01:38 GMT</pubDate>
            <atom:updated>2023-12-20T12:01:38.851Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<p>When you first start out in web automation, it’s all about taking the right actions in the right order. But as you advance, timing becomes more and more important.</p><p>A great script minimizes the amount of time it spends waiting for changes, and it parallelizes as much behavior as possible. Faster scripts save you time and money, and the work it takes to make them more robust as well.</p><p>This article will cover the ins and outs of working with time in Playwright. Cut your scripts from taking minutes to seconds.</p><p>And if this post is helpful, visit my deep dive on working with <a href="https://www.browsercat.com/post/strengthen-selectors-and-locators-in-playwright">Playwright locators</a>. I cover optimizing your Playwright scripts for speed, scale, and stability in much greater detail.</p><p>Let’s dive in!</p><h3>Use the Correct Wait Strategy</h3><p>By default, Playwright’s locators will wait for at least one matching element to appear on the page. In many cases, this is all you need, but the deeper you get into automation, the more frequently this strategy will fall short.</p><p>Often, you’ll need to watch for other criteria before a particular locator is ready for action. Here’s a good example of why you can’t always trust the default wait strategy:</p><pre>// 🟢 GOOD: The default wait works for a single matching element<br>const $modal = page.locator(&#39;#signup-modal&#39;);<br>// 🔴 BAD: But it fails when you need to wait for multiple elements<br>const $confetti = page.locator(&#39;.confetto&#39;);</pre><h3>Wait for global state</h3><p>The “dynamic confetti” problem above can be solved by waiting for the global state to normalize.</p><pre>// Wait for at least 100 confetti<br>await page.waitForFunction(async () =&gt; {<br>  return await page.locator(&#39;.confetto&#39;).count() &gt;= 100;<br>});<br>const $confetti = page.locator(&#39;.confetto&#39;);</pre><p>page.waitForFunction() will run the function until the return is truthy. This allows you to write very clean code that&#39;s equally powerful.</p><h3>Embrace the State of the Locator</h3><p>Locators normally resolve when at least one matching DOM node is attached to the DOM. However, Playwright offers a few other convenience methods:</p><pre>// Attached when added to the DOM (default)<br>const $attached = page.getByRole(&#39;button&#39;)<br>  .waitFor({state: &#39;attached&#39;});<br><br>// Detached when removed from the DOM<br>const $detached = page.getByRole(&#39;button&#39;)<br>  .waitFor({state: &#39;detached&#39;});<br>// Visible when attached and has some visible pixels<br>const $attached = page.getByRole(&#39;button&#39;)<br>  .waitFor({state: &#39;visible&#39;});<br>// Hidden when detached, `visibility: hidden`, or `display: none`<br>const $attached = page.getByRole(&#39;button&#39;)<br>  .waitFor({state: &#39;hidden&#39;});</pre><p>The visible state will frequently come in handy, as a lot of dynamic HTML works by managing visibility rather than dynamically creating new subtrees.</p><h3>Set a Custom Timeout</h3><p>By default, Playwright will resolve a locator as soon as it possibly can. But if you’re waiting on a dynamically added list of elements, you may prefer to set an extended timeout.</p><pre>// Wait for a waterfall of injected JS script tags<br>const $dynamicScripts = page.locator(&#39;script&#39;)<br>  .waitFor({timeout: 60_000});</pre><p>That said, use caution with the timeout approach. If you find yourself leaning on such an imprecise tool, you may want to look twice for better solutions. After all, you can potentially save a lot of time by targeting the precise event that will allow your script to proceed.</p><p>Here’s one particular strategy…</p><h3>Wait for DOM Events</h3><p>Sometimes, it’s best to go back to basics and lean on the DOM to ensure the necessary content is loaded before proceeding with your selectors.</p><p>For example, let’s say that you need a particular image to have loaded before taking a screenshot of the page. You might use the load event to ensure that this is the case:</p><pre>const $logo = page.getByRole(&#39;img&#39;)<br>  .and(page.getByAltText(&#39;BrowserCat&#39;));<br><br>$logo.evaluate(($el) =&gt; {<br>  return new Promise((resolve) =&gt; {<br>    $el.addEventListener(&#39;load&#39;, resolve, {once: true});<br>  });<br>});<br><br>// Logo is loaded!<br>await $logo.screenshot();</pre><p>It’s worth highlighting the power of Playwright’s .evaluate() API. This simple construct gives you direct access to the browser context. Use it to get down to the metal, and control the flow of your scripts directly.</p><h3>Use Asynchronous Interactions</h3><p>The longer your scripts become, the more you’ll gain by running page interactions simultaneously. Playwright’s websocket communication model makes this very performant, and the Locator API is in fact built with asynchronous code in mind.</p><p>Let’s dive into some strategies worth remembering…</p><h3>Reuse Locators with Dynamic Content</h3><p>Playwright’s locators are dynamic by design, which means they resolve fresh each time they’re accessed. This is particularly handy when dealing with changeable content on a web page.</p><pre>const $messages = page.locator(&#39;#chat li&#39;);<br>let prevMessage = null;<br><br>// listen for websocket messages<br>page.on(&#39;websocket&#39;, (socket) =&gt; {<br>  socket.on(&#39;framereceived&#39;, async (event) =&gt; {<br>    const lastMessage = await $messages.last().textContent();<br>    // verify the new message was added to the chat list<br>    assert(lastMessage !== prevMessage);<br>    prevMessage = lastMessage;<br>  });<br>});</pre><p>In this example, we access the locator every time a websocket message is received, then we verify that the new message is added to the chat list.</p><p>Notice that the $messages locator is reused without being replaced. This unlocks the possibility of defining your primary locators in the initialization of your script, reusing them as necessary across otherwise complex automations.</p><h3>Run Tasks in Parallel</h3><p>Often, scripts wait for one task to complete before starting another. But this isn’t a necessary restriction. In Playwright, you can achieve easy parallelism just by employing Promise.all, saving a lot of time in the process.</p><pre>const result = await Promise.all([<br>  // Starts a long-running calculation...<br>  page.locator(&#39;#long-running-calculation&#39;).click(),<br>  // Waits for the calculation result to come through...<br>  page.waitForResponse((res) =&gt; /calculation-results/.test(res.url())),<br>]).then(() =&gt; {<br>  // Retrieve the result<br>  return page.locator(&#39;.calculation-results&#39;).textContent();<br>});<br><br>console.log(&#39;Calculation completed. Results:&#39;, result);</pre><p>With Promise.all, the script initiates the calculation and waits for the resulting response simultaneously, rather than sequentially. When leveraged strategically, this can shave off precious seconds or even minutes from the total run time.</p><h3>Leverage a Dependency Graph</h3><p>Sometimes, you have tasks that depend on others but needn’t run in a singular chain. In these cases, you can create a dependency graph by initializing numerous promises, but only awaiting the results at the end of your script. This will ensure that every interaction happens both in the correct order and as swiftly as possible.</p><p>This is a somewhat contrived example, but it’s not difficult to scale the pattern up. You will assuredly find reasons to do so in your own code.</p><pre>const doLogin = page.locator(&#39;#login&#39;).click();<br>const loadDashboard = doLogin.then(() =&gt; page.waitForNavigation({<br>  url: /dashboard/,<br>}));<br>const fetchData = page.waitForResponse((res) =&gt; {<br>  return /data-endpoint/.test(res.url());<br>});<br><br>// Do more stuff here...<br><br>const [dashboardLoaded, apiResponse] = await Promise.all([loadDashboard, fetchData]);<br>console.log(&#39;Dashboard has loaded!&#39;);<br>console.log(&#39;API data:&#39;, await apiResponse.json());</pre><p>By setting up a structure of chained promises, this example initializes various tasks, but only forces those chains to resolve at the very end. Less time wasted, more money saved.</p><h3>Next steps</h3><p>Now that you’re brimming with ideas on how to speed up your scripts, go play! Every automation is a little different. The more you experiment, the more you’ll learn.</p><p>And if you’re curious about more ways to optimize your Playwright automations, check out my <a href="https://www.browsercat.com/post/strengthen-selectors-and-locators-in-playwright">Playwright locator deep-dive</a>.</p><p>Remember, timing is everything. Happy automating!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=616663f62043" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplify and Stabilize Your Playwright Locators]]></title>
            <link>https://medium.com/@mikestopcontinues/simplify-and-stabilize-your-playwright-locators-35b36b437480?source=rss-83cb14ea8e7a------2</link>
            <guid isPermaLink="false">https://medium.com/p/35b36b437480</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[playwright-test]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Mike Stop Continues]]></dc:creator>
            <pubDate>Tue, 19 Dec 2023 12:02:10 GMT</pubDate>
            <atom:updated>2023-12-19T12:02:10.284Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<p>Who controls the locators, controls the web.</p><p>Much of Playwright’s power comes from its ability to target and interact with elements on a webpage. But as you well know, the web is a finicky place. Elements come and go, and the slightest change in HTML can break your automation scripts.</p><p>In this article, we’ll explore strategies for creating simple and stable Playwright locators that can withstand the test of time and changes in web applications. We’ll also look at how to optimize your selectors for speed and efficiency.</p><p>For a more in-depth look at these concepts, check out my complete deep dive on <a href="https://www.browsercat.com/post/strengthen-selectors-and-locators-in-playwright">optimizing Playwright locators</a>.</p><p>Let’s go!</p><h3>Optimize Selector Specificity</h3><p>Refining selector specificity involves finding an ideal equilibrium: you need selectors that are precise enough to unambiguously identify target elements across different page states, yet not so intricate that they shatter with the slightest DOM adjustments.</p><p>Steer clear of overly rigid selectors; such fragility means that a trivial HTML modification could render them useless. On the flip side, too loose selectors might lead you down a path of position-dependent logic (like indices) or unwarranted reliance on the web page’s current implementation.</p><p>We’re looking for the Goldilocks zone of search queries.</p><p>Here are a few anti-patterns and how to fix them:</p><pre>// 🔴 BAD: Selectors based on fragile structural assumptions<br>const $link = page.locator(&#39;li:nth-child(3) &gt; a&#39;);<br>// 🟢 GOOD: Selectors grounded in distinguishing features<br>const $link = page.locator(&#39;a[href*=&quot;privacy&quot;]&#39;);<br><br>// 🔴 BAD: Selectors anchored to mutable text<br>const $button = page.locator(&#39;button&#39;, {hasText: &#39;Sign up&#39;});<br>// 🟢 GOOD: Robust, pattern-based selectors<br>const $button = page.locator(&#39;button&#39;, {<br>  hasText: /(sign|start|subscribe|launch)/i,<br>});<br><br>// 🔴 BAD: Selectors tied to changeable style-specific classes<br>const $input = page.locator(&#39;input.email&#39;);<br>// 🟢 GOOD: Selectors focused on functional attributes<br>const $input = page.locator(&#39;input[type=&quot;email&quot;]&#39;);<br><br>// 🔴 BAD: Excessively specific hierarchical selectors<br>const $list = page.locator(&#39;footer &gt; ul.inline-links &gt; li&#39;);<br>// 🟢 GOOD: Shallow, adaptive nesting<br>const $list = page.locator(&#39;footer:last-of-type li&#39;, {<br>  has: page.locator(&#39;a&#39;),<br>});</pre><p>To sum up:</p><ul><li>Prioritize attributes that capture the essence of the target element, rather than arbitrary qualities.</li><li>If your target elements have no stable defining characteristics, anchor your queries to parents or children who do have such qualities.</li><li>Keep chain selectors short, and try to only use stable elements within them.</li><li>Leverage regular expressions for text matching to accommodate variations.</li></ul><h3>Prefer Semantic Locator Methods</h3><p>When it comes to selecting elements, it’s always better to prioritize semantic attributes over stylistic or functional attributes. While an element’s classes or its location in the DOM are typically the easiest to target, they’re also the most prone to change. On the other hand, semantic attributes (such as role, label, or title) change infrequently. And when they do, they tend to change in ways that can be accounted for ahead of time.</p><p>Given the benefit of targeting semantic attributes, Playwright provides utility methods for directly accessing them. Use them whenever possible. Here’s why:</p><ul><li>Semantic methods encourage best practices. As you’ll see in the passages that follow, the most durable selector patterns have helper methods.</li><li>Semantic methods are typed, improving your IDE experience and alerting you to errors. Plain selector strings can only be debugged at runtime, resulting in more bugs.</li><li>Semantic methods are chainable. This dramatically simplifies the queries themselves. It also results in better error messages when queries fail.</li></ul><p>Let’s run through each method that’s currently available:</p><pre>// Target Test IDs when you have control of the HTML<br>// E.G. `&lt;section data-testid=&quot;delete-modal&quot; /&gt;`<br>const $modal = page.getByTestId(&#39;delete-modal&#39;);<br><br>// Target explicit or implied element roles<br>// &quot;button&quot; matches `&lt;button&gt;`, `&lt;input type=&quot;button&quot;&gt;`, or `&lt;div aria-role=&quot;button&quot;&gt;`<br>const $button = page.getByRole(&#39;button&#39;, {hasText: &#39;Buy&#39;});<br><br>// Target text HTML attributes that are unlikely to change<br>const $input = page.getByLabel(&#39;Email&#39;);<br>const $search = page.getByPlaceholder(/^search/i);<br>const $image = page.getByAltText(&#39;Profile Picture&#39;);<br>const $icon = page.getByTitle(&#39;Info&#39;, {exact: false});<br><br>// Or target elements by `innerText`, when you can be sure it&#39;s stable<br>const $dialog = page.getByText(/^confirm/i);</pre><p>I cannot stress enough how valuable it is to target based on role and data-testid in particular.</p><p>When you have control of the DOM, data-testid is a fantastic <a href="https://markdown-to-medium.surge.sh/glossary/data-testid">convention</a> to implement across dev teams. Unlike every other HTML attribute, there is never any reason for data-testid to change, making it the least brittle of all possible selectors.</p><p>That said, given that you won’t always have control over the HTML of target pages, role is an excellent fallback. As shown in the example code above, role is an inherently forgiving selector. It can continue working even across substantial DOM changes.</p><h3>Chain Locators, Not Selectors</h3><p>As described above, it’s best to avoid long selector query strings. They’re inherently difficult to debug, and they result in less descriptive error messages.</p><p>Of course, you’re not always going to be able to avoid chaining. Sometimes, you need to target particularly evasive DOM nodes. More often, you simply want to break a page up into subtrees and drill down from an intermediate HTML element. (For example, a list of articles in a blog feed.)</p><p>Here are two strategies for designing locators that are both easy to read and easy to debug…</p><h3>Drill Down Within Subtrees</h3><p>Chaining locators is like adding layers to a sketch; each additional stroke refines the image. Begin with a broad locator and use methods like .filter(), .first(), .last(), and conditional parameters to progressively narrow down to your target element.</p><pre>// Find the first article about BrowserCat<br>const $articles = page.locator(&#39;article&#39;);<br>const $aboutBrowserCat = $articles.filter({<br>  hasText: /BrowserCat/i<br>});<br>const $firstArticle = $aboutBrowserCat.first();</pre><p>This approach separates concerns, ties the locators to logical entities, and keeps the code readable and adaptable. If your layout changes, you might only need to adjust the parent locator instead of unraveling multiple complex strings.</p><h3>Filter by Content with {has} and {hasNot}</h3><p>Sometimes you need to select an element not only by its properties but also by its relation to others. With {has} and {hasNot} parameters, you can define these relationships clearly, creating a robust context for your selectors.</p><pre>// Find the first article with an image<br>const $articles = page.locator(&#39;article&#39;);<br>const $withImages = $articles.filter({ <br>  has: page.locator(&#39;img&#39;),<br>});<br>const $firstArticle = $withImages.first();</pre><p>These parameters act as assertions about the presence of certain elements within a parent. This increases the number of stable, unique attributes you can leverage in creating good query patterns.</p><h3>Next steps</h3><p>We’ve touched on several key practices for creating simple and stable Playwright locators that can withstand the test of time and changes in web applications. I go much deeper on performance, error handling, and refactoring your selectors in my <a href="https://www.browsercat.com/post/strengthen-selectors-and-locators-in-playwright">Playwright locators deep-dive</a>. Check it out.</p><p>Until next time, happy automating!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35b36b437480" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What are Playwright Locators and Selectors?]]></title>
            <link>https://medium.com/@mikestopcontinues/what-are-playwright-locators-and-selectors-578380bc4a88?source=rss-83cb14ea8e7a------2</link>
            <guid isPermaLink="false">https://medium.com/p/578380bc4a88</guid>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[playwright-test]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Mike Stop Continues]]></dc:creator>
            <pubDate>Mon, 18 Dec 2023 12:01:38 GMT</pubDate>
            <atom:updated>2023-12-18T12:01:38.095Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<p>Playwright is a Swiss Army knife for browser automation, and nearly all of Playwright’s expansive functionality is based on two core tools: selectors and locators. They’re essential for anyone serious about working with Playwright, and they’re the focus of this article.</p><p>In the following post, we’ll cover what they are, why they matter, and how to use them effectively. Once you understand the basics, visit my deep dive on <a href="https://www.browsercat.com/post/strengthen-selectors-and-locators-in-playwright">strengthening your Playwright locators</a>. It’s a great resource for truly mastering these tools.</p><p>Let’s get started!</p><h3>What are Playwright Selectors?</h3><p>Playwright selectors are search queries used to match elements within the page’s DOM. They leverage various strategies such as CSS, XPath, textual content, pseudo-selectors, and even custom properties you define. Selectors are strings, and they are the foundation of Playwright’s locators, though they don’t enable interaction by themselves.</p><p>Here are some examples:</p><pre>// create a locator using css<br>const $buttonByCSS = page.locator(&#39;css=button&#39;);<br><br>// create a locator using xpath<br>const $buttonByXPath = page.locator(&#39;xpath=//button&#39;);<br><br>// create a locator using psuedo-selectors<br>const $buttonByRole = page.getByRole(&#39;button&#39;);</pre><p>Playwright also allows the registration of custom selectors, leveraging any logic you can dream up. At first blush, this might seem like overkill, but as code matures and you develop domain logic, custom selectors can dramatically simplify your code.</p><p>Here’s a brief taste:</p><pre>// target elements currently within a particular shadow DOM<br>await selectors.register(&#39;shadow&#39;, createShadowSelector);<br><br>// query all options within a custom select web component<br>const $options = page.locator(&#39;shadow=x-custom-select option&#39;);<br>await $options.count();</pre><p>We’ll return to this technique later with a complete example.</p><h3>What are Playwright Locators?</h3><p>Locators are a powerful abstraction built on top of selectors. They provide a clean interface for selecting elements, interacting with them, and traversing the DOM subtree within them. You use them <em>constantly</em> in Playwright.</p><p>As an improvement over the now-deprecated $() API, they also come with some unique advantages. First, they are always up-to-date. A selector that targets a list of elements will always select the full list, no matter how many items have been added, removed, or changed.</p><p>And second, locators will wait until the selector pattern finds a match on the page. This is incredibly useful when working with dynamic content, as you no longer have to build arbitrary or complex timeout logic into your scripts.</p><p>We’ll cover locators in great detail later, but here’s a quick sample:</p><pre>// find the button with `name=&quot;submit&quot;`<br>const $submitButton = page.getByRole(&#39;button&#39;, {name: &#39;submit&#39;});<br>// or...<br>const $submitButton = page.locator(&#39;role=button&#39;, {name: &#39;submit&#39;});<br><br>// click it!<br>await $submitButton.click();</pre><p>Locators can also be chained to increase specificity without having to resort to long selector queries. Example:</p><pre>const $taskList = page.locator(&#39;ul#tasks&#39;);<br>const $taskLinks = $taskList.locator(&#39;a&#39;);<br>const $completedTasks = $taskLinks.filter({<br>  has: page.locator(&#39;input[type=&quot;checkbox&quot;]:checked&#39;),<br>});</pre><h3>Next steps</h3><p>By now, you should have a solid understanding of Playwright locators and selectors. To dive deeper, make sure you check out my everything guide to <a href="https://www.browsercat.com/post/strengthen-selectors-and-locators-in-playwright">strengthening your Playwright locators</a>.</p><p>Happy automating!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=578380bc4a88" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Block Ads in Playwright with an Adblocker]]></title>
            <link>https://medium.com/@mikestopcontinues/block-ads-in-playwright-with-an-adblocker-a1f2dc9884d2?source=rss-83cb14ea8e7a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1f2dc9884d2</guid>
            <category><![CDATA[playwrights]]></category>
            <category><![CDATA[scraping]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Mike Stop Continues]]></dc:creator>
            <pubDate>Fri, 01 Dec 2023 04:01:50 GMT</pubDate>
            <atom:updated>2023-12-01T04:01:50.748Z</atom:updated>
            <content:encoded><![CDATA[<p>Playwright is such a powerful technology because it gives you programmatic access to a full web browser. However, that means it also suffers from the same weaknesses as the browser. Anything that slows down a human browsing the web also slows down your scripts.</p><p>Not least among these _slow-downs_ are online ads, trackers, and other annoyances. By preventing these third party resources from loading, we can improve performance, improve stability, and decrease cost.</p><p>This article covers how you can efficiently reduce the load of ads and trackers within Playwright scripts for an optimal automation experience. If you’re interested in going deeper into resource management and optimization, you’ll love my <a href="https://www.browsercat.com/post/block-inline-and-network-resources-with-playwright">Playwright resource deep-dive</a>.</p><p>Let’s get started…</p><h3>Block Ads With Built-In Methods</h3><p>A straightforward method to stop ads and trackers is to block them by domain. For websites that have minimal dependencies on third-party domains, this is an effective and no-extra-dependency solution:</p><pre>// watch all network activity<br>await page.route(&#39;**/*&#39;, (route) =&gt; {<br>  // abort requests from known ad domains<br>  if (route.request().url().includes(&#39;cdn.ads.com&#39;)) {<br>    route.abort();<br>  } else {<br>    route.continue();<br>  }<br>});</pre><p>This is an excellent first step in managing ads during a Playwright job, but it’s also quite limited. Firstly, it requires that you keep track of all the third-parties you want to block on your target site. And second, it requires that you know ahead of time which websites your script will run on. After all, your tool might load sites selected by your end users, or it might crawl multiple arbitrary sites during runtime.</p><h3>Embed an Ad Blocker</h3><p>Just like in a real browser, you can run an adblocker in your Playwright scripts, leveraging huge open-source blacklists of known offenders.</p><p>While this strategy depends on an external library, it’s by far the best way to block wasteful web traffic in your automations.</p><p>From all the options out there, I recommend `@cliqz/adblocker-playwright`. It’s a great library with clean docs and great config options (if you even need them). Let’s set it up…</p><h4>Getting Started with `@cliqz/adblocker-playwright`</h4><p>It all starts with installing the package:</p><pre>npm install --save @cliqz/adblocker-playwright</pre><p>Then set it up like so:</p><pre>import * as pw from &#39;playwright&#39;;<br>import { PlaywrightBlocker } from &#39;@cliqz/adblocker-playwright&#39;;<br><br>const browser = await pw.chromium.launch();<br>const context = await browser.newContext();<br><br>const blocker = await PlaywrightBlocker.fromPrebuiltAdsAndTracking(fetch);<br><br>blocker.enableBlockingInContext(context);</pre><p>By tapping into an up-to-date list of ad sources and trackers, this strategy efficiently filters out unwanted noise. And if you need more control, well, you got it…</p><h4>Pick Your Favorite Blacklists</h4><p>Perhaps you’ve got a custom blacklist. Or perhaps you want to include a few of the open-source lists maintained by good webizens. `@cliqz/adblocker` supports leveraging both local and remote blacklists.</p><p>Here’s an example:</p><pre>import { readFileSync } from &#39;fs&#39;;<br>import { PlaywrightBlocker } from &#39;@cliqz/adblocker-playwright&#39;;<br><br>const blocker = await PlaywrightBlocker.fromLists(fetch, [<br>  &#39;https://easylist.to/easylist/easylist.txt&#39;,<br>]);<br><br>blocker.enableBlockingInContext(context);</pre><p>Interested in picking some custom lists? I suggest starting with [EasyList](https://easylist.to/), then if you discover gaps, search the web. There are many, many options.</p><h3>Next Steps…</h3><p>These ad-blocking strategies with Playwright pave the way for cleaner automation workflows, better performance, and enhanced security. But this is only one tool in your Playwright optimization toolkit. Be sure to explore my in-depth guide on managing <a href="https://www.browsercat.com/post/block-inline-and-network-resources-with-playwright">Playwright resources</a>. It has a lot of great tips packed as densely together as I could fit them.</p><p>In the meantime, happy automating!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1f2dc9884d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>