<?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 Adam Pajda on Medium]]></title>
        <description><![CDATA[Stories by Adam Pajda on Medium]]></description>
        <link>https://medium.com/@adam_pajda?source=rss-1526527ab524------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*GsgBafg-Xbcx31-qtP9dzg.jpeg</url>
            <title>Stories by Adam Pajda on Medium</title>
            <link>https://medium.com/@adam_pajda?source=rss-1526527ab524------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 14:39:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@adam_pajda/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[Learning programming and Leveraging AI: A Journey to Better Feedback and Growth]]></title>
            <link>https://medium.com/@adam_pajda/learning-programming-and-leveraging-ai-a-journey-to-better-feedback-and-growth-eed59e661516?source=rss-1526527ab524------2</link>
            <guid isPermaLink="false">https://medium.com/p/eed59e661516</guid>
            <category><![CDATA[leadership]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[feedback]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Adam Pajda]]></dc:creator>
            <pubDate>Sun, 26 Jan 2025 12:54:38 GMT</pubDate>
            <atom:updated>2025-01-26T12:54:38.916Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h18PJSWRkvn8PnZ_dipwig.jpeg" /></figure><p>Finishing the book <em>Thanks for the Feedback</em> by Douglas Stone and Sheila Heen has been an insightful journey. The book delves deeply into how we receive feedback — an essential skill that often goes unaddressed. As an engineering leader and a test engineer in IT, I couldn’t help but reflect on how the principles of feedback reception align with a crucial aspect of my work: code review.</p><h3>The Challenge of Feedback in Code Review</h3><p>In software development, code reviews are a cornerstone of collaboration and quality assurance. However, they’re also a frequent source of tension. Engineers can feel attacked or demotivated when their work is critiqued. This mirrors the themes in <em>Thanks for the Feedback</em>: the emotional, identity, and relationship triggers that can make feedback — even constructive feedback — hard to accept.</p><p>One key takeaway from the book is the idea that feedback is as much about the receiver as it is about the giver. In the context of code reviews, this means that while reviewers must strive for clarity and kindness, developers also need to build resilience and openness to grow from the feedback they receive.</p><h3>Using <a href="https://www.coderabbit.ai/">CodeRabbit.ai</a> to Enhance Learning from Feedback</h3><p>As I pondered how we can make feedback a tool for learning rather than a source of conflict, I thought about the potential of CodeRabbit.ai. This AI tool, could be a game-changer in how we adapt to feedback in technical contexts. Additionally, <strong>CodeRabbit.ai is free for open-source projects</strong>, making it accessible for learners to use without financial barriers.</p><h4>How CodeRabbit.ai Can Be Used</h4><ol><li><strong>Simulating Feedback Scenarios</strong>: CodeRabbit.ai could simulate code review scenarios, providing feedback on sample code with varying tones and levels of detail. Engineers could practice interpreting and responding to these comments constructively.</li><li><strong>Real-time Insights</strong>: During actual coding projects, Rabbit.ai could analyze pull requests and suggest ways to incorporate feedback effectively. For example, if an engineer receives a review asking for refactoring, the tool could suggest resources or code patterns to implement the requested changes.</li><li><strong>Learning from Patterns</strong>: By analyzing historical feedback data, Rabbit.ai could identify recurring themes in reviews — such as a tendency to overlook edge cases — and recommend targeted learning paths to address these gaps.</li><li><strong>Building Psychological Safety</strong>: One of the principles from <em>Thanks for the Feedback</em> is creating environments where feedback feels safe and constructive. Rabbit.ai could help by identifying patterns of overly harsh language or unbalanced feedback in reviews, suggesting ways to reframe comments to be more productive.</li></ol><h3>Adapting to Feedback</h3><p>The key to receiving feedback is not just accepting it but actively using it to fuel growth. <em>Thanks for the Feedback</em> emphasizes the importance of identifying the type of feedback being given: appreciation, coaching, or evaluation. In code reviews, distinguishing between these types can help developers respond more effectively.</p><ul><li><strong>Appreciation</strong>: When reviewers acknowledge good practices or clever solutions, it’s important to take note and reinforce those behaviors.</li><li><strong>Coaching</strong>: Feedback aimed at improving specific aspects of the code or coding style should be seen as an opportunity to learn. Rabbit.ai could play a critical role here by offering suggestions to implement the advice.</li><li><strong>Evaluation</strong>: Feedback that measures performance against a standard — such as adherence to coding guidelines — can be the hardest to hear. However, it’s vital for setting a baseline for growth.</li></ul><h3>Learning Go and Improving Skills</h3><p>Currently, I am learning Go, a programming language known for its simplicity and efficiency. I use Go not only to improve my technical skills but also to enhance my ability to learn and adapt. Working with Go has been a practical way to apply the feedback I receive in code reviews and to experiment with the concepts from <em>Thanks for the Feedback</em>. This focused approach has helped me grow both as an engineer and as a learner.</p><h3>Conclusion</h3><p>Integrating the lessons from <em>Thanks for the Feedback</em> into the code review process can transform it from a dreaded ritual into a powerful learning experience. Tools like Rabbit.ai have the potential to bridge the gap between feedback and action, making it easier for engineers to adapt and thrive.</p><p>Ultimately, the goal is to create a culture where feedback — whether in code reviews or other areas — is embraced as a gift. By combining human insights with AI-powered tools, we can build teams that are not only technically strong but also resilient and open to continuous improvement.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eed59e661516" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Playwright Visual Tests with GIT-LFS and Docker]]></title>
            <link>https://medium.com/@adam_pajda/playwright-visual-tests-with-git-lfs-and-docker-d537ddd6e86a?source=rss-1526527ab524------2</link>
            <guid isPermaLink="false">https://medium.com/p/d537ddd6e86a</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[qa]]></category>
            <category><![CDATA[playwright-test]]></category>
            <dc:creator><![CDATA[Adam Pajda]]></dc:creator>
            <pubDate>Sat, 14 Dec 2024 10:38:33 GMT</pubDate>
            <atom:updated>2024-12-14T13:41:06.749Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IL81HIi2gv3p4ZXLO5olyg.jpeg" /></figure><p>While working on various projects, I struggled to find a good solution for managing golden screenshots in Playwright — so I decided to share my approach, hoping it helps others facing the same challenge! All examples and source code are available <a href="https://github.com/pajdekPL/playwright-git-lfs">here</a>. I assume you are familiar with Playwright, Git and Docker.</p><p>This guide explains how to set up and use Git Large File Storage (LFS) to efficiently manage golden/baseline screenshots in your Playwright visual testing workflow. Additionally, it provides a Docker-based solution for generating consistent golden screenshots across different platforms, ensuring reliable visual testing in CI environments.</p><h3>Table of Contents</h3><ol><li>Why Git LFS for Visual Testing?</li><li>Setup Instructions</li><li>Building and Running PW in Docker — golden screenshots generation</li><li>Screenshot Management Strategy</li><li>PullRequest example</li><li>Best Practices</li><li>Common Issues and Solutions</li><li>Conclusion</li></ol><h3>Why Git LFS for Visual Testing?</h3><p>When performing visual testing with Playwright, you need to store baseline (golden) screenshots to compare against during test runs. These image files can quickly increase your repository size. Git LFS helps by:</p><ol><li>Storing large files outside of regular Git</li><li>Replacing image files with lightweight pointers in your Git repository</li><li>Improving repository clone and pull times</li><li>Making it more efficient to work with binary files</li></ol><h3>Benefits of Version-Controlled Screenshots</h3><p>Keeping screenshots in your repository (via Git LFS) provides several key advantages:</p><ol><li><strong>Team Collaboration</strong>: Team members can review and approve visual changes through standard Git workflows</li><li><strong>Change History</strong>: Track the evolution of your UI over time with full history of visual changes</li><li><strong>Code Review Integration</strong>: Review visual changes alongside code changes in pull requests</li><li><strong>Accountability</strong>: Know who made specific visual changes and when they were made</li><li><strong>Rollback Capability</strong>: Easily revert to previous versions of screenshots if needed</li><li><strong>CI/CD Integration</strong>: Automated visual testing in CI/CD pipelines with consistent baselines</li></ol><h3>Setup Instructions</h3><h4>1. Install Git LFS</h4><pre># macOS (using Homebrew)<br>brew install git-lfs<br># Initialize Git LFS<br>git lfs install</pre><p>For other platforms, refer to the official Git LFS documentation: <a href="https://git-lfs.com/">https://git-lfs.com</a></p><h4>2. Configure Git LFS for Screenshots</h4><p>Create a .gitattributes file in your repository root and specify which files should be tracked by Git LFS:</p><pre># Track all PNG files in the tests directory<br>tests/**/*.png filter=lfs diff=lfs merge=lfs -text</pre><h4>3. Set up Playwright Visual Testing</h4><p>In your Playwright configuration (playwright.config.ts), configure the screenshots directory:</p><pre>export default defineConfig({<br>  testDir: &#39;./tests&#39;,<br>  snapshotDir: &quot;./screenshots&quot;,<br>// rest of your Playwright config<br>});</pre><h3>Usage</h3><h4>Creating Baseline Screenshots</h4><ol><li>Write your visual test:</li></ol><pre>import { test, expect } from &#39;@playwright/test&#39;;<br><br>test(&#39;homepage visual test&#39;, async ({ page }) =&gt; {<br>  await page.goto(&#39;https://your-website.com&#39;);<br>  await expect(page).toHaveScreenshot(&#39;homepage.png&#39;);<br>});</pre><p>2. Generate baseline screenshots:</p><pre><br>npx playwright test --update-snapshots</pre><p>3. Track new screenshots with Git LFS</p><p>Once Git LFS is set up, you can use Git as you normally would — just use regular git add, git commit, and git push commands. Git LFS works seamlessly in the background, automatically handling the screenshot files based on your .gitattributes configuration.</p><pre>git add tests/screenshots<br>git commit -m &quot;Add baseline screenshots&quot;<br>git push</pre><h4>Running Visual Tests</h4><p>Regular test runs will compare against the baseline images:</p><pre>npx playwright test</pre><h3>Building and Running PW in Docker — golden screenshots generation</h3><p>Most CI environments run on Linux machines, so it’s important to maintain Linux-specific screenshots for consistent visual testing. If you’re developing on macOS, you’ll need to generate the Linux screenshots using Docker:</p><p>Use this cmd to start the Docker container(with the hardcoded Playwright version):</p><pre>docker run --rm \<br>  --network host \<br>  --ipc=host \<br>  -v &quot;$(pwd)&quot;:/work/ \<br>  -w /work/ \<br>  -it mcr.microsoft.com/playwright:v1.49.0-noble \<br>  /bin/bash -c &quot;npm install &amp;&amp; bash&quot;</pre><p>Or use the <a href="https://github.com/pajdekPL/playwright-git-lfs/blob/main/run-pw-docker.sh">run-pw-docker.sh</a> script that will automatically detect Playwright version and run the correct Docker image:</p><pre>chmod +x run-pw-docker.sh<br>./run-pw-docker.sh</pre><p>Now you should be in docker, you can for example generate golden screenshots that are used for CI execution:</p><pre>npx playwright test --grep &quot;YOUR TEST&quot; --update-snapshots</pre><p>The script uses jq to parse Playwright version from npm list, if you don&#39;t have it, you can install it using brew install jq.</p><p>These Linux-generated screenshots will ensure consistency with your CI environment, preventing false positives in visual regression tests that might occur due to platform-specific rendering differences. If you don’t have Docker installed the free alterantive for MAC is <a href="https://colima.dev/">Colima</a>. You can install it using:</p><pre>brew install colima<br>brew install docker<br>colima start</pre><h3>PullRequest Example</h3><p><a href="https://github.com/pajdekPL/playwright-git-lfs/pull/1/files">Here</a> you can find how easy it is to compare golden screenshots update.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*27fHcCm4PfbA9ghJgQI3uA.png" /></figure><h3>Screenshot Management Strategy</h3><p>We use a specific naming convention and Git configuration to manage screenshots effectively.</p><p>Only Linux-generated screenshots are stored in the repository (used for CI), create .<strong>gitignore</strong> file with:</p><pre># .gitignore <br>*.png <br>!*-linux.png</pre><p>This configuration:</p><ul><li>Ignores all PNG files by default</li><li>Explicitly tracks only screenshots with -linux.png suffix</li><li>Ensures consistent visual testing in CI environment</li></ul><p>This approach:</p><ul><li>Reduces repository size by storing only essential screenshots</li><li>Ensures consistent visual testing in CI pipeline</li><li>Prevents conflicts from different OS-specific renderings</li></ul><h3>Best Practices</h3><ol><li><strong>Organize Screenshots</strong>: Keep a clear directory structure for screenshots, e.g., by feature or component.</li><li><strong>Meaningful Names</strong>: Use descriptive names for screenshot files that indicate what they represent.</li><li><strong>Tagging</strong>: Use tags to labeling visual tests, such as @visual-regression or @visual-test.</li><li><strong>Review Changes</strong>: Always review screenshot changes before committing them.</li><li><strong>CI Setup</strong>: Ensure your CI environment has Git LFS installed and configured.</li></ol><h3>Common Issues and Solutions</h3><h4>Large Repository Size</h4><ul><li>Regularly clean up unused screenshots</li><li>Consider using .gitattributes to track only specific directories</li></ul><h4>Team Collaboration</h4><ul><li>Ensure all team members have Git LFS installed locally</li><li>Team members must run git lfs pull after cloning or pulling changes to download the actual screenshot files</li><li>Without Git LFS installed, team members will only see pointer files instead of actual screenshots</li></ul><h4>CI/CD Integration</h4><ul><li>Install Git LFS in your CI environment:</li></ul><pre>- name: Install Git LFS<br>  run: |<br>    git lfs install<br>    git lfs pull</pre><h4>Git Hooks Integration</h4><ul><li>When using Husky with Git LFS, be aware that they use different Git hooks structures</li><li>Husky may need additional configuration to work alongside Git LFS hooks</li><li>You might need to manually add Git LFS hooks to your Husky configuration:</li></ul><pre>{<br>  &quot;hooks&quot;: {<br>    &quot;pre-push&quot;: &quot;git lfs push --all origin &amp;&amp; your-other-hooks&quot;,<br>    &quot;post-checkout&quot;: &quot;git lfs checkout&quot;,<br>    &quot;post-merge&quot;: &quot;git lfs checkout&quot;<br>  }<br>}</pre><h3>Conclusion</h3><p>Using Git LFS for Playwright visual test screenshots provides an efficient way to manage your test assets while keeping your repository performant. It allows team members to easily share and update baseline images while maintaining good version control practices. Please also consider using Docker for consistenc.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d537ddd6e86a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[API Testing with Playwright and OpenAPI-Generated Types]]></title>
            <link>https://medium.com/@adam_pajda/api-testing-with-playwright-and-openapi-generated-types-7c530f7d2cb6?source=rss-1526527ab524------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c530f7d2cb6</guid>
            <category><![CDATA[qa]]></category>
            <category><![CDATA[playwright-test]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[test-automation]]></category>
            <dc:creator><![CDATA[Adam Pajda]]></dc:creator>
            <pubDate>Sun, 08 Dec 2024 18:46:18 GMT</pubDate>
            <atom:updated>2024-12-14T10:23:09.038Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oQ3Byz2zTVAEho_GxNlfOw.jpeg" /></figure><p>This article demonstrates how to create a robust API testing framework using PlayWright and OpenAPI documentation. Examples are based on the <a href="https://automationintesting.online/">Restful-Booker Platform</a>, a purpose-built API testing playground. The Restful-Booker Platform provides a realistic environment for learning and practicing API testing techniques, featuring authentication, room management, and other common API operations.</p><p>All code examples are available under this <a href="https://github.com/pajdekPL/playwright-api-testing">repository</a>.</p><h3>Table of Contents</h3><ol><li>Project Setup</li><li>Project Structure</li><li>OpenAPI Type Generation</li><li>Building Type-Safe API Clients</li><li>Creating API Tests</li><li>Best Practices</li><li>Final Suggestions</li></ol><h3>Project Setup</h3><p>First, set up a new project with the necessary dependencies:</p><pre>npm init playwright@latest<br>npm install -D openapi-typescript <br>npm install dotenv # For managing environment variables</pre><p>Create a .env file in the root of your project to store environment variables:</p><pre>USERNAME=admin<br>PASSWORD=password<br>BASE_API_URL=https://automationintesting.online/</pre><p>Configure TypeScript in tsconfig.json:</p><pre>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;target&quot;: &quot;ES2021&quot;,<br>    &quot;module&quot;: &quot;commonjs&quot;,<br>    &quot;baseUrl&quot;: &quot;.&quot;,<br>    &quot;esModuleInterop&quot;: true,<br>    &quot;strict&quot;: true,<br>    &quot;paths&quot;: {<br>      &quot;@api/*&quot;: [&quot;src/api/*&quot;],<br>      &quot;@expects/*&quot;: [&quot;src/expects/*&quot;],<br>      &quot;@models/*&quot;: [&quot;src/models/*&quot;],<br>      &quot;@fixtures/*&quot;: [&quot;src/fixtures/*&quot;]<br>    }<br>  }<br>}</pre><p>Import and configure dotenv at the beginning of your playwright.config.ts file:</p><pre>import dotenv from &#39;dotenv&#39;;<br>dotenv.config();<br>export const BASE_API_URL = process.env.BASE_API_URL || &#39;default-url&#39;;<br>// Rest of your Playwright configuration</pre><h3>Project Structure</h3><p>Organize your project with the following structure to maintain clarity and manageability:</p><pre>project-root/<br>│<br>├── src/<br>│   ├── api/<br>|   |   ├── base-api-client.ts<br>│   │   ├── fetch-helpers.ts<br>│   │   ├── api-statuses.ts<br>│   │   ├── api-clients/<br>│   │   │   ├── rooms-api-client.ts<br>│   │   │   └── auth-api-client.ts<br>│   │   ├── types/<br>│   │   │   ├── room.d.ts<br>│   │   │   └── auth.d.ts<br>│   │   └── fixtures/<br>│   │       ├── api.fixture.ts<br>│   └── tests/<br>│       └── api/<br>│           └── rooms.api.spec.ts<br>│<br>├── .env<br>├── playwright.config.ts<br>├── package.json<br>└── tsconfig.json</pre><p>This structure separates API clients, types, and tests, making it easier to navigate and maintain your codebase. The api directory contains all API-related files, including clients and generated types.</p><h3>OpenAPI Type Generation</h3><p>Install the required package:</p><pre>npm install -D openapi-typescript # You can skip this if you finished the previous step</pre><p>In this article, we will use two APIs: the Room API and the Auth API. Download their respective OpenAPI/Swagger specifications:</p><ul><li><strong>Room API</strong>: <a href="https://automationintesting.online/room/v3/api-docs/room-api">room.json</a></li><li><strong>Auth API</strong>: <a href="https://automationintesting.online/auth/v3/api-docs/auth-api">auth.json</a></li></ul><p>Generate TypeScript types using the command:</p><pre>npx openapi-typescript room.json -o room.d.ts npx openapi-typescript auth.json -o auth.d.ts</pre><p>Ensure you have both specifications to generate the necessary TypeScript types for our API clients. You can copy and paste the JSON files directly into your project folder with names room.json and auth.json, or you can use curl to download them from the links provided above. Move the generated .d.ts files to the appropriate directory under src/api/types/</p><h3>Fetch Helpers</h3><p>The fetch-helpers.ts file contains utility functions and types that simplify making HTTP requests. It provides a consistent way to handle API requests and responses, ensuring that all API interactions are type-safe and follow a standard pattern.</p><h4>Contents of fetch-helpers.ts</h4><ul><li><strong>FetchConfig</strong>: A type that defines the configuration for making requests, including base URL and headers.</li><li><strong>FetchOptions</strong>: A type that specifies options for individual requests, such as method, headers, and body.</li><li><strong>FetchResponse</strong>: A type that represents the response from an API request, including status and data.</li><li><strong>fetchWithConfig</strong>: A function that performs an HTTP request using the provided configuration and options, returning a FetchResponse.</li></ul><p>These helpers ensure that API requests are made consistently across the project, reducing code duplication and potential errors. By using TypeScript types, they also provide compile-time checks for request and response data, improving overall code quality.</p><p>Here’s an example of what the fetch-helpers.ts might look like:</p><pre>// src/api/fetch-helpers.ts<br>import { APIRequestContext } from &quot;@playwright/test&quot;;<br>export interface FetchConfig {<br>  baseURL: string;<br>  headers: Record&lt;string, string&gt;;<br>  validateStatus?: (status: number) =&gt; boolean;<br>}<br>export interface FetchResponse&lt;T = unknown&gt; {<br>  status: number;<br>  statusText: string;<br>  data: T;<br>  headers: Record&lt;string, string&gt;;<br>}<br>export interface FetchOptions&lt;T = unknown&gt; {<br>  method?: string;<br>  headers?: Record&lt;string, string&gt;;<br>  data?: T;<br>  params?: Record&lt;string, string | number | boolean | undefined&gt;;<br>}<br>export async function fetchWithConfig&lt;T&gt;(<br>  request: APIRequestContext,<br>  url: string,<br>  options: FetchOptions&lt;T&gt; = {},<br>): Promise&lt;FetchResponse&lt;T&gt;&gt; {<br>  const { method = &quot;GET&quot;, headers = {}, data, params } = options;<br>  // Build URL with query parameters<br>  const urlObj = new URL(url);<br>  if (params) {<br>    Object.entries(params).forEach(([key, value]) =&gt; {<br>      if (value !== undefined) {<br>        urlObj.searchParams.append(key, String(value));<br>      }<br>    });<br>  }<br>  const response = await request.fetch(urlObj.toString(), {<br>    method,<br>    headers,<br>    data: data !== undefined ? JSON.stringify(data) : undefined,<br>  });<br>  const responseData = (await response.json().catch(() =&gt; null)) as T;<br>  const responseHeaders = response.headers();<br>  return {<br>    status: response.status(),<br>    statusText: response.statusText(),<br>    data: responseData,<br>    headers: responseHeaders,<br>  };<br>}</pre><h3>Using Generated Types</h3><p>Before implementing API clients, let’s create an api-statuses.ts file to define API status codes.</p><pre>// src/api/api-statuses.ts<br>export const API_STATUSES = {<br>  SUCCESSFUL_200_STATUS: 200,<br>  CREATED_201_STATUS: 201,<br>  ACCEPTED_202_STATUS: 202,<br>  ACCESS_DENIED_403_STATUS: 403,<br>  NO_CONTENT_204_STATUS: 204,<br>  NOT_FOUND_404_STATUS: 404,<br>  UNAUTHORIZED_401_STATUS: 401,<br>  UNPROCESSABLE_ENTITY_422_STATUS: 422,<br>};</pre><h3>Using Playwright Custom Expect</h3><p>We will also need a new custom expect extension to extend Playwright’s expect capabilities in order to make API assertions more readable and maintainable. Please create the following api-expects.ts under the src/expects directory:</p><pre>// src/expects/api-expects.ts<br>import { expect as baseExpect } from &quot;@playwright/test&quot;;<br>import { FetchResponse } from &quot;@api/fetch-helpers&quot;;<br>export { test } from &quot;@playwright/test&quot;;<br>export const expect = baseExpect.extend({<br>  toHaveStatusCode(<br>    response: FetchResponse,<br>    status: number<br>  ): { pass: boolean; message: () =&gt; string } {<br>    let pass: boolean;<br>    let matcherResult: string;<br>    try {<br>      baseExpect(response.status).toBe(status);<br>      pass = true;<br>      matcherResult = &quot;Passed&quot;;<br>    } catch (error) {<br>      matcherResult = `${String(error)}, statusText: ${<br>        response.statusText<br>      } response data: ${JSON.stringify(<br>        response.data<br>      )} headers: ${JSON.stringify(response.headers)}`;<br>      pass = false;<br>    }<br>    return {<br>      message: () =&gt; matcherResult,<br>      pass: pass,<br>    };<br>  },<br>});</pre><p>Let’s implement our API clients using the generated types:</p><pre>// api/base-api-client.ts<br>import {<br>  FetchConfig,<br>  FetchOptions,<br>  FetchResponse,<br>  fetchWithConfig,<br>} from &quot;@api/fetch-helpers&quot;;<br>import { APIRequestContext } from &quot;@playwright/test&quot;;<br>export type RequestParams&lt;TData = unknown&gt; = Omit&lt;<br>  FetchOptions&lt;TData&gt;,<br>  &quot;data&quot;<br>&gt; &amp; {<br>  data?: TData;<br>};<br><br>export class BaseApiClient {<br>  protected request: APIRequestContext;<br>  protected config: FetchConfig;<br>  protected basePath: string;<br>  constructor(<br>    config: FetchConfig,<br>    request: APIRequestContext,<br>    basePath: string<br>  ) {<br>    this.config = config;<br>    this.request = request;<br>    this.basePath = basePath;<br>  }<br>  protected async makeRequest&lt;T, D extends T = T&gt;(<br>    endpoint: string,<br>    options: RequestParams&lt;D&gt; = {}<br>  ): Promise&lt;FetchResponse&lt;T&gt;&gt; {<br>    const url = new URL(endpoint, this.config.baseURL).toString();<br>    return fetchWithConfig&lt;T&gt;(this.request, url, {<br>      ...options,<br>      headers: {<br>        ...this.config.headers,<br>        ...options.headers,<br>      },<br>    });<br>  }<br>}</pre><h3>API Client Example</h3><pre>// src/api/api-clients/rooms-api-client.ts<br>import { BaseApiClient } from &quot;@api/base-api-client&quot;;<br>import { FetchConfig, FetchResponse } from &quot;@api/fetch-helpers&quot;;<br>import type { components } from &quot;@api/types/room&quot;;<br>import { APIRequestContext } from &quot;@playwright/test&quot;;<br>import { BASE_API_URL } from &quot;playwright.config&quot;;<br>import { expect } from &quot;@expects/api-expects&quot;;<br>import { API_STATUSES } from &quot;@api/statuses.api&quot;;<br>export type Room = components[&quot;schemas&quot;][&quot;Room&quot;];<br>export type Rooms = components[&quot;schemas&quot;][&quot;Rooms&quot;];<br>interface RoomQueryParams {<br>  roomName?: string;<br>  type?: string;<br>  accessible?: boolean;<br>  [key: string]: string | boolean | undefined;<br>}<br>export const ROOMS_API_URL = new URL(&quot;/room/&quot;, BASE_API_URL).toString();<br>export class RoomsApiClient extends BaseApiClient {<br>  constructor(config: FetchConfig, request: APIRequestContext) {<br>    super(config, request, &quot;/room/&quot;);<br>  }<br>  async getRoomsRaw(params?: RoomQueryParams): Promise&lt;FetchResponse&lt;Rooms&gt;&gt; {<br>    return this.makeRequest&lt;Rooms, never&gt;(this.basePath, {<br>      method: &quot;GET&quot;,<br>      params,<br>    });<br>  }<br>  async getRooms(params?: RoomQueryParams): Promise&lt;Rooms&gt; {<br>    const response = await this.getRoomsRaw(params);<br>    expect(response).toHaveStatusCode(API_STATUSES.SUCCESSFUL_200_STATUS);<br>    return response.data;<br>  }<br>  async getRoomRaw(id: number): Promise&lt;FetchResponse&lt;Room&gt;&gt; {<br>    return this.makeRequest&lt;Room, never&gt;(`${this.basePath}${id}`, {<br>      method: &quot;GET&quot;,<br>    });<br>  }<br>  async getRoom(id: number): Promise&lt;Room&gt; {<br>    const response = await this.getRoomRaw(id);<br>    expect(response).toHaveStatusCode(API_STATUSES.SUCCESSFUL_200_STATUS);<br>    return response.data;<br>  }<br>  async createRoomRaw(data: Room): Promise&lt;FetchResponse&lt;Room&gt;&gt; {<br>    return this.makeRequest&lt;Room, Room&gt;(this.basePath, {<br>      method: &quot;POST&quot;,<br>      data,<br>    });<br>  }<br>  async createRoom(data: Room): Promise&lt;Room&gt; {<br>    const response = await this.createRoomRaw(data);<br>    expect(response).toHaveStatusCode(API_STATUSES.CREATED_201_STATUS);<br>    return response.data;<br>  }<br>  async updateRoomRaw(id: number, data: Room): Promise&lt;FetchResponse&lt;Room&gt;&gt; {<br>    return this.makeRequest&lt;Room, Room&gt;(<br>      new URL(`${id}`, this.basePath).toString(),<br>      {<br>        method: &quot;PUT&quot;,<br>        data,<br>      }<br>    );<br>  }<br>  async updateRoom(id: number, data: Room): Promise&lt;Room&gt; {<br>    const response = await this.updateRoomRaw(id, data);<br>    expect(response).toHaveStatusCode(API_STATUSES.SUCCESSFUL_200_STATUS);<br>    return response.data;<br>  }<br>  async deleteRoomRaw(id: number): Promise&lt;FetchResponse&lt;null&gt;&gt; {<br>    return this.makeRequest&lt;null, never&gt;(`${this.basePath}${id}`, {<br>      method: &quot;DELETE&quot;,<br>    });<br>  }<br>  async deleteRoom(id: number): Promise&lt;void&gt; {<br>    const response = await this.deleteRoomRaw(id);<br>    expect(response).toHaveStatusCode(API_STATUSES.ACCEPTED_202_STATUS);<br>  }<br>}<br>export function createRoomsApiClient(<br>  request: APIRequestContext,<br>  cookies = &quot;&quot;,<br>  token = &quot;&quot;<br>): RoomsApiClient {<br>  const config: FetchConfig = {<br>    baseURL: BASE_API_URL,<br>    headers: {<br>      &quot;X-api-version&quot;: &quot;1.0&quot;,<br>      &quot;content-type&quot;: &quot;application/json;charset=UTF-8&quot;,<br>      Cookie: cookies,<br>      Authorization: token ? `Bearer ${token}` : &quot;&quot;,<br>    },<br>    validateStatus: () =&gt; true,<br>  };<br>  return new RoomsApiClient(config, request);<br>}</pre><h3>Authentication API Client Example</h3><p>In order to use the rooms client with authentication, we’ll create an authentication API client:</p><pre>// src/api/api-clients/auth-api-client.ts<br>import { BaseApiClient } from &quot;@api/base-api-client&quot;;<br>import { FetchConfig, FetchResponse } from &quot;@api/fetch-helpers&quot;;<br>import { API_STATUSES } from &quot;@api/statuses.api&quot;;<br>import type { components } from &quot;@api/types/auth&quot;;<br>import { expect } from &quot;@expects/api-expects&quot;;<br>import { APIRequestContext } from &quot;@playwright/test&quot;;<br>import { BASE_API_URL } from &quot;playwright.config&quot;;<br><br>export const AUTH_API_URL = new URL(&quot;/auth/&quot;, BASE_API_URL).toString();<br>export type Auth = components[&quot;schemas&quot;][&quot;Auth&quot;];<br>export type Token = components[&quot;schemas&quot;][&quot;Token&quot;];<br><br>export class AuthApiClient extends BaseApiClient {<br>  constructor(config: FetchConfig, request: APIRequestContext) {<br>    super(config, request, &quot;/auth/&quot;);<br>  }<br>  async loginRaw(data: Auth): Promise&lt;FetchResponse&lt;Auth&gt;&gt; {<br>    return this.makeRequest&lt;Auth&gt;(`${this.basePath}login`, {<br>      method: &quot;POST&quot;,<br>      data,<br>    });<br>  }<br>  async login(data: Auth): Promise&lt;FetchResponse&gt; {<br>    const response = await this.loginRaw(data);<br>    expect(response).toHaveStatusCode(API_STATUSES.SUCCESSFUL_200_STATUS);<br>    return response;<br>  }<br>  async loginAndReturnToken(data: Auth): Promise&lt;string&gt; {<br>    const response = await this.login(data);<br>    const setCookie = response.headers[&quot;set-cookie&quot;];<br>    if (!setCookie) {<br>      throw new Error(&quot;Token not found in response headers&quot;);<br>    }<br>    const cookieValue =<br>      typeof setCookie === &quot;string&quot; ? setCookie : setCookie[0];<br>    const tokenMatch = /token=([^;]+)/.exec(cookieValue);<br>    if (!tokenMatch) {<br>      throw new Error(&quot;Token format not recognized in cookie&quot;);<br>    }<br>    return tokenMatch[1];<br>  }<br>  async validateToken(token: string): Promise&lt;FetchResponse&lt;Token&gt;&gt; {<br>    const response = await this.makeRequest&lt;Token&gt;(`${this.basePath}validate`, {<br>      method: &quot;POST&quot;,<br>      data: { token },<br>    });<br>    if (!response.data?.token) {<br>      throw new Error(&quot;Invalid token response from server&quot;);<br>    }<br>    return response;<br>  }<br>  async clearToken(token: string): Promise&lt;FetchResponse&lt;Token&gt;&gt; {<br>    return this.makeRequest&lt;Token&gt;(`${this.basePath}logout`, {<br>      method: &quot;POST&quot;,<br>      data: { token },<br>    });<br>  }<br>}<br>export function createAuthApiClient(<br>  request: APIRequestContext,<br>  token = &quot;&quot;,<br>  cookies = &quot;&quot;<br>): AuthApiClient {<br>  const config: FetchConfig = {<br>    baseURL: BASE_API_URL,<br>    headers: {<br>      &quot;X-api-version&quot;: &quot;1.0&quot;,<br>      &quot;content-type&quot;: &quot;application/json;charset=UTF-8&quot;,<br>      Cookie: cookies ? `token=${cookies}` : &quot;&quot;,<br>      Authorization: token ? `Bearer ${token}` : &quot;&quot;,<br>    },<br>    validateStatus: () =&gt; true,<br>  };<br>  return new AuthApiClient(config, request);<br>}</pre><h3>Creating API Tests</h3><h3>Using Playwright Fixtures</h3><p>Playwright’s fixtures provide a powerful way to handle test setup and teardown. Instead of using beforeEach, we can create reusable fixtures that manage API client lifecycle and authentication. Please create the following fixture api.fixture.ts under the src/fixtures directory:</p><pre>// src/fixtures/api.fixture.ts<br>import { test as base, APIRequestContext } from &quot;@playwright/test&quot;;<br>import {<br>  RoomsApiClient,<br>  createRoomsApiClient,<br>} from &quot;@api/api-clients/rooms-api-client&quot;;<br>import {<br>  AuthApiClient,<br>  createAuthApiClient,<br>  Auth,<br>} from &quot;@api/api-clients/auth-api-client&quot;;<br>interface ApiFixtures {<br>  roomsApiClient: RoomsApiClient;<br>  authApiClient: AuthApiClient;<br>  roomsAuthenticatedApiClient: RoomsApiClient;<br>}<br>export const test = base.extend&lt;ApiFixtures&gt;({<br>  roomsApiClient: async ({ request }, use) =&gt; {<br>    const roomsApiClient = createRoomsApiClient(request);<br>    await use(roomsApiClient);<br>  },<br>  authApiClient: async ({ request }, use) =&gt; {<br>    const authApiClient = createAuthApiClient(request);<br>    await use(authApiClient);<br>  },<br>  roomsAuthenticatedApiClient: async ({ request }, use) =&gt; {<br>    const user: Auth = {<br>      username: process.env.USERNAME,<br>      password: process.env.PASSWORD,<br>    };<br>    const token = await loginUserAndGetToken(request, user);<br>    const cookies = `token=${token}`;<br>    const roomsApiClient = createRoomsApiClient(request, cookies, &quot;&quot;);<br>    await use(roomsApiClient);<br>  },<br>});<br>// Helper function for authentication<br>async function loginUserAndGetToken(<br>  request: APIRequestContext,<br>  user: Auth<br>): Promise&lt;string&gt; {<br>  const authApiClient = createAuthApiClient(request);<br>  const token = await authApiClient.loginAndReturnToken(user);<br>  return token.replace(/^token=/, &quot;&quot;);<br>}</pre><h3>Test Examples</h3><pre>// tests/api/rooms.api.spec.ts<br>import { test } from &quot;@fixtures/api-fixtures&quot;;<br>import { expect } from &quot;@playwright/test&quot;;<br>import type { Room } from &quot;@api/api-clients/rooms-api-client&quot;;<br>test.describe(&quot;Rooms API&quot;, () =&gt; {<br>  test(&quot;should create and retrieve a room as authenticated user&quot;, async ({<br>    roomsAuthenticatedApiClient: client,<br>  }) =&gt; {<br>    const newRoom: Room = {<br>      roomName: &quot;Suite 101&quot;,<br>      type: &quot;Double&quot;,<br>      accessible: true,<br>      roomPrice: 100,<br>    };<br>    const createdRoom = await client.createRoom(newRoom);<br>    expect(createdRoom.roomName).toBe(newRoom.roomName);<br>    const room = await client.getRoom(createdRoom.roomid as number);<br>    expect(room).toEqual(createdRoom);<br>  });<br>  test(&quot;should handle room deletion scenarios&quot;, async ({<br>    roomsAuthenticatedApiClient: client,<br>  }) =&gt; {<br>    // Create a room to delete<br>    const roomToDelete: Room = {<br>      roomName: &quot;Temporary Room&quot;,<br>      type: &quot;Double&quot;,<br>      accessible: true,<br>      roomPrice: 100,<br>      description: &quot;Room to be deleted&quot;,<br>    };<br>    // Create and verify the room exists<br>    const createdRoom = await client.createRoom(roomToDelete);<br>    expect(createdRoom.roomid).toBeTruthy();<br>    // Delete the room<br>    await client.deleteRoom(createdRoom.roomid!);<br>    // Verify the room no longer exists<br>    const getRoomPromise = client.getRoom(createdRoom.roomid!);<br>    // 500 error is how our API handles getting a non-existent room<br>    await expect(getRoomPromise).rejects.toThrow(/500/);<br>    // Attempt to delete non-existent room<br>    const deleteNonExistentPromise = client.deleteRoom(99999);<br>    await expect(deleteNonExistentPromise).rejects.toThrow(/404/);<br>  });<br>});</pre><h3>Best Practices</h3><p>By combining Playwright’s powerful testing capabilities with TypeScript and OpenAPI-generated types, you can create a robust, type-safe API testing framework. This approach helps catch errors early, improves maintainability, and provides excellent developer experience through IDE support and auto-completion.</p><p>Remember to keep your OpenAPI specification up-to-date and regenerate types when the API changes. This ensures your tests always reflect the current state of your API contract.</p><p>Creating dedicated API clients is a great way of building a maintainable API testing framework. Here’s why:</p><ul><li><strong>Type Safety</strong>: API clients encapsulate the OpenAPI-generated types, ensuring type-safe requests and responses.</li><li><strong>Code Reusability</strong>: Instead of duplicating API calls across tests, we centralize them in dedicated clients.</li><li><strong>Response Validation</strong>: We can enforce consistent response status code checks and error handling.</li><li><strong>Maintainability</strong>: When API endpoints change, we only need to update the client, not individual tests.</li><li><strong>Better Developer Experience</strong>: IDE autocompletion for request/response types makes writing tests easier.</li></ul><h3>Key Takeaways</h3><ul><li><strong>Maintainability</strong>: Centralize API logic in clients to reduce duplication.</li><li><strong>Type Safety</strong>: Leverage TypeScript and OpenAPI for robust type checking.</li><li><strong>Automation</strong>: Use CI/CD pipelines to automate type generation and testing.</li><li><strong>Documentation</strong>: Keep your APIs and tests well-documented.</li><li><strong>Fixtures</strong>: Use fixtures to simplify setup and teardown.</li></ul><p>Feel free to explore more advanced testing strategies and tools to further enhance your API testing framework!</p><h3>Final Suggestions</h3><p>To successfully implement API testing frameworks like the one described in this article, it’s crucial to have comprehensive and up-to-date API documentation. This ensures that all team members and automated systems have a clear understanding of the API’s capabilities and expected behaviors.</p><p>Using strong typing, as demonstrated with TypeScript and OpenAPI-generated types, not only enhances code quality and maintainability but also facilitates the generation of tests using AI tools. Strong typing provides a clear contract for what the API expects and returns, which can be leveraged by AI to automate test generation and validation, improving both efficiency and accuracy.</p><p>By integrating these practices, you can create a robust, scalable, and efficient API testing framework that adapts to evolving requirements and technologies.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c530f7d2cb6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>