<?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 Pankaj Kumar Shee on Medium]]></title>
        <description><![CDATA[Stories by Pankaj Kumar Shee on Medium]]></description>
        <link>https://medium.com/@sheepankaj?source=rss-94140a0f703------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*oHVqNWDYdWargEiT</url>
            <title>Stories by Pankaj Kumar Shee on Medium</title>
            <link>https://medium.com/@sheepankaj?source=rss-94140a0f703------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 22:14:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sheepankaj/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[Scaling Playwright Automation with Docker, Kubernetes and GitHub Actions]]></title>
            <link>https://medium.com/@sheepankaj/scaling-playwright-automation-with-docker-kubernetes-and-github-actions-79e062dc27c9?source=rss-94140a0f703------2</link>
            <guid isPermaLink="false">https://medium.com/p/79e062dc27c9</guid>
            <category><![CDATA[automation-testing]]></category>
            <category><![CDATA[parallel-test-execution]]></category>
            <category><![CDATA[software-test-automation]]></category>
            <category><![CDATA[docker-kubernetes]]></category>
            <category><![CDATA[github-actions]]></category>
            <dc:creator><![CDATA[Pankaj Kumar Shee]]></dc:creator>
            <pubDate>Wed, 28 Oct 2026 16:36:07 GMT</pubDate>
            <atom:updated>2026-10-28T21:12:28.774Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi All, Welcome back to another blog of mine.</p><p>In my previous blog, I shared how I used Playwright with k6 for load testing and generated an HTML report to review the results.</p><p>This time, I wanted to explore something different. I wanted to understand how we can use Docker and Kubernetes to run Playwright automation tests in a distributed way.</p><p>As QA automation engineers, we often start by writing test cases and running them on our local machines. This works well when the test suite is small. But what happens when an application has hundreds or thousands of test cases?</p><p>Running all tests on one machine can take a long time. We may also need to test the application in different browsers, environments and versions.</p><p>This is where parallel and distributed test execution can help.</p><p>For this project, I used Playwright, Docker, GitHub Actions and AWS Elastic Kubernetes Service (EKS). I used existing demo websites and APIs so that I could focus on the automation framework and infrastructure instead of building a new application.</p><p>Let’s see how it works.</p><h3>What are we going to build?</h3><p>The goal of this project is to explore how we can package Playwright tests, run them in parallel and distribute the workload across multiple machines or Kubernetes Pods.</p><p>Here is what I have included:</p><ol><li><strong>Playwright</strong> — for UI and API automation testing.</li><li><strong>Docker</strong> — to package the test framework and its required environment.</li><li><strong>GitHub Actions</strong> — to run tests automatically and publish the Docker image.</li><li><strong>Playwright sharding</strong> — to split a large test suite into smaller parts.</li><li><strong>AWS EKS and Kubernetes</strong> — to run the test shards across multiple Pods.</li><li><strong>HTML reporting</strong> — to combine test results into a report that is easier to review.</li></ol><p>You can find the complete project here:</p><p><strong>GitHub repository:</strong> <a href="https://github.com/sheepankaj/playwrightdockerkubernetestesting-lab">https://github.com/sheepankaj/playwrightdockerkubernetestesting-lab</a></p><h3>1. Creating the Playwright test framework</h3><p>First, I created a Playwright framework using TypeScript.</p><p>For this project, I used two public demo services:</p><ul><li><strong>SauceDemo</strong> for UI automation.</li><li><strong>Swagger Petstore</strong> for API automation.</li></ul><p>The UI tests cover interactions with the demo application, while the API tests validate requests and responses from the Petstore API.</p><p>I organised the framework into separate folders to make it easier to maintain and extend.</p><pre>playwrightdockerkubernetestesting-lab/<br>├── framework/<br>│   ├── api/<br>│   ├── pages/<br>│   ├── support/<br>│   ├── testdata/<br>│   └── utils/<br>├── tests/<br>│   ├── ui/<br>│   └── api/<br>├── k8s/<br>│   ├── configmap.yaml<br>│   ├── namespace.yaml<br>│   └── playwright-job.yaml<br>├── .github/<br>│   └── workflows/<br>├── Dockerfile<br>├── playwright.config.ts<br>└── package.json</pre><p>The framework folder contains reusable components, and the tests folder contains the actual test cases.</p><p>I also used reusable page objects for UI testing and an API client for the API tests.</p><p>The first step is to make sure the tests run correctly before introducing Docker or Kubernetes.</p><p>For example, we can run the tests locally using:</p><pre>npm install<br>npx playwright install<br>npm test</pre><p>Once the framework is working, we can look at how to run it in a consistent environment and distribute the execution.</p><h3>2. Why do we need Docker?</h3><p>Docker allows us to package the test framework and the environment it needs into a container image.</p><p>This is useful for Playwright because browser automation depends on specific browser binaries and system dependencies.</p><p>Without a consistent environment, tests might work on one machine but fail on another because of differences in configuration or installed dependencies.</p><p>For this project, I used the official Playwright Docker image as the base image.</p><p>The Dockerfile installs the project dependencies and copies the framework into the image.</p><p>We can build the image with:</p><pre>docker build -t playwright-tests .</pre><p>Then we can run the tests inside a container:</p><pre>docker run --env-file .env playwright-tests</pre><p>The .env file contains the environment variables required by the tests. It should not be committed to a public repository if it contains sensitive information.</p><p>The main advantage is that we can reuse the same packaged test environment in different places, including local Docker, CI pipelines and Kubernetes.</p><h3>3. Splitting tests using Playwright sharding</h3><p>Now let’s look at one of the most important parts of this project: sharding.</p><p>Imagine that we have a test suite containing hundreds of test cases. Instead of running the entire suite in one execution, we can split it into smaller groups.</p><p>Playwright supports this through its --shard option. For example:</p><pre>npx playwright test --shard=1/3</pre><p>This command runs the first shard out of three. The other two shards can run using:</p><pre>npx playwright test --shard=2/3<br>npx playwright test --shard=3/3</pre><p>Each shard runs a different part of the test suite. Sharding and workers are related, but they are not the same thing.</p><ul><li><strong>Sharding</strong> splits the test suite into separate groups.</li><li><strong>Workers</strong> allow multiple tests to run concurrently within a single Playwright execution.</li></ul><p>For example, three shards with two workers per shard can provide up to six concurrent test workers, assuming the tests and available resources allow it. This gives us a way to distribute test execution rather than depending on a single process.</p><h3>4. Automating test execution using GitHub Actions</h3><p>Once the test framework is ready, we need a way to execute it automatically.</p><p>For this, I used GitHub Actions. GitHub Actions allows us to define workflows that run when certain events happen in a repository, such as a push or a pull request.</p><p>In my project, the workflow runs Playwright tests using three separate shards on GitHub-hosted runners.</p><p>After the test jobs finish, another job merges the generated reports. The workflow also builds and publishes a multi-architecture Docker image to GitHub Container Registry (GHCR) when the configured branch is updated and the tests pass.<br>The workflow looks like this:</p><pre>Code pushed to GitHub<br>                    |<br>                    v<br>             GitHub Actions<br>                    |<br>          +---------+---------+<br>          |         |         |<br>          v         v         v<br>        Shard 1   Shard 2   Shard 3<br>          |         |         |<br>          +---------+---------+<br>                    |<br>                    v<br>           Merge test reports<br>                    |<br>                    v<br>            Generate HTML report</pre><pre>          After successful tests:<br>                    |<br>                    v<br>             Build Docker image<br>                    |<br>                    v<br>          Publish image to GHCR</pre><p>In the latest workflow run, the GitHub Actions pipeline completed in approximately 2 minutes and 39 seconds. This includes the CI jobs, report processing and Docker image publishing. It is the pipeline duration, not a measurement of the Kubernetes execution time.</p><p>You can see the run here:</p><p><a href="https://github.com/sheepankaj/playwrightdockerkubernetestesting-lab/actions/runs/40680328124">https://github.com/sheepankaj/playwrightdockerkubernetestesting-lab/actions/runs/40680328124</a></p><p>One important design decision is that the GitHub Actions test jobs run directly on GitHub-hosted runners rather than inside the Docker image.</p><p>I chose this approach to keep CI execution straightforward and avoid pulling and starting the test container for every shard.</p><p>The Docker image is built and published separately so that it can be used by Kubernetes.</p><p>This means GitHub Actions and Docker have different responsibilities in the project.</p><p><strong>Screenshots from Githib Actipons pipeline:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mjOxL2OaziZrJr3APb-SHQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*zfDlLpBrQXTx7USNc_1rsw.png" /></figure><h3>5. Running Playwright tests in AWS EKS</h3><p>Now let’s move to Kubernetes.</p><p>Kubernetes helps us manage containerised workloads. It schedules Pods, manages their execution and allows us to configure resource limits.</p><p>AWS EKS is Amazon’s managed Kubernetes service. It allows us to run Kubernetes workloads on AWS without managing the Kubernetes control plane ourselves.</p><p>For this project, I created a Kubernetes Job configured to run the Playwright test suite across three Pods in one EKS cluster.</p><p>Each Pod runs a different Playwright shard.<br>The architecture looks like this:</p><pre>AWS EKS Cluster<br>                     |<br>              Kubernetes Job<br>                     |<br>          +----------+----------+<br>          |          |          |<br>          v          v          v<br>        Pod 1      Pod 2      Pod 3<br>        Shard 1    Shard 2    Shard 3<br>          |          |          |<br>          v          v          v<br>       Playwright test execution</pre><p>Instead of running all the tests inside one Pod, Kubernetes can schedule the three Pods to run in parallel, subject to available resources.</p><p>Each Pod uses the same Docker image but receives a different shard number.</p><p>The Kubernetes Job uses an indexed completion value to identify the shard assigned to each Pod. This means I do not need to maintain three separate copies of the test framework.</p><p>The configuration also defines CPU and memory resources and the environment variables required by the tests.</p><p>This is the key difference between running tests with multiple workers on one machine and distributing them across Kubernetes Pods.</p><p>With workers, we are using the resources available to one execution environment. With Kubernetes, we can distribute the workload across Pods and potentially across different worker nodes.</p><h3>6. How I run the tests on AWS EKS</h3><p>One practical part of this project was getting the tests to run in my AWS environment.</p><p>My current AWS account setup does not allow me to complete the GitHub Actions-to-EKS authentication and deployment workflow using OIDC. Because of that, I currently trigger the Kubernetes execution manually through AWS CloudShell.</p><p>The GitHub Actions pipeline still runs the tests and publishes the Docker image automatically. I then use CloudShell to connect to EKS and apply the Kubernetes Job.</p><p>This is not a fully automated end-to-end deployment yet, but it allowed me to test the Kubernetes execution using a real AWS environment.</p><h3>Step 1: Connect to the EKS cluster</h3><p>AWS CloudShell provides a terminal with AWS CLI tools and access to the credentials available in the AWS console session.<br>After opening CloudShell, I clone the repository:</p><pre>git clone https://github.com/sheepankaj/playwrightdockerkubernetestesting-lab.git<br>cd playwrightdockerkubernetestesting-lab</pre><p>Then I configure kubectl to connect to my EKS cluster:</p><pre>aws eks update-kubeconfig \<br>  --region eu-north-1 \<br>  --name playwrighttest</pre><p>To check the cluster nodes:</p><pre>kubectl get nodes</pre><h3>Step 2: Apply the Kubernetes configuration</h3><p>First, I create the namespace and apply the ConfigMap:</p><pre>kubectl apply -f k8s/namespace.yaml<br>kubectl apply -f k8s/configmap.yaml</pre><p>The namespace keeps the project resources organised, while the ConfigMap contains non-sensitive configuration values.</p><p>I also create a Kubernetes Secret for the test credentials and API configuration. Sensitive values should not be committed to the repository or included directly in public documentation.</p><h3>Step 3: Start the test execution</h3><p>Before starting a new run, I remove the previous Job if it exists:</p><pre>kubectl delete job playwright-test-run \<br>  -n playwright \<br>  --ignore-not-found=true</pre><p>Then I apply the Kubernetes Job:</p><pre>kubectl apply -f k8s/playwright-job.yaml</pre><p>Kubernetes creates the Pods according to the Job configuration.</p><h3>Step 4: Monitor the Pods</h3><p>To watch the Pods:</p><pre>kubectl get pods -n playwright -w</pre><p>Each Pod is responsible for one shard of the test suite.</p><p>I can also view the logs from all the test Pods:</p><pre>kubectl logs -n playwright \<br>  -l app=playwright-tests \<br>  --prefix=true</pre><p>This helps me inspect the test output and understand what happened during each shard’s execution.</p><p>If a Pod encounters a problem, I can inspect its details and events:</p><pre>kubectl describe pod &lt;pod-name&gt; -n playwright</pre><p>For example, ImagePullBackOff can indicate a problem retrieving the Docker image, while OOMKilled indicates that a container exceeded its memory limit.</p><p>This is an important part of working with distributed automation: we need to understand not only the test results but also the infrastructure running the tests.</p><h3>7. Collecting and merging the test reports</h3><p>When tests run on different machines or Pods, their report files are not automatically combined into one report.</p><p>For the GitHub Actions workflow, I configured the report-merging job to combine the shard results into a single downloadable HTML report.</p><p>For the Kubernetes execution, each Pod produces its own blob report.</p><p>After the Job completes, I can copy the report files from the three Pods into one folder and merge them using Playwright.</p><p>The process is:</p><pre>Kubernetes Pod 1<br>          Blob report<br>               \<br>        Kubernetes Pod 2 ----&gt; Combined folder<br>          Blob report        /<br>               /                   |<br>        Kubernetes Pod 3            v<br>          Blob report          Merge reports<br>                                    |<br>                                    v<br>                              HTML report</pre><p>The commands below illustrate the report collection step from a terminal that has access to the EKS cluster and the required local tools:</p><pre>mkdir blob-report-all</pre><pre>kubectl cp playwright/playwright-test-run-0:/app/blob-report/. ./blob-report-all<br>kubectl cp playwright/playwright-test-run-1:/app/blob-report/. ./blob-report-all<br>kubectl cp playwright/playwright-test-run-2:/app/blob-report/. ./blob-report-all</pre><p>Then I merge the collected reports:</p><pre>npx playwright merge-reports \<br>  --reporter html ./blob-report-all</pre><p>Finally, I can open the report:</p><pre>npx playwright show-report</pre><p>This provides a single report for reviewing the results from the distributed execution.</p><p>For a larger enterprise implementation, I would consider uploading the reports to shared object storage such as Amazon S3 or using shared storage. That would make report collection easier and reduce the need to copy files manually.</p><p><strong>Screenshots from the Kubernetes:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MyHsVN3nYF_KbhmLqWDYQg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FuW0sZ6OtS0nteX-JpXzZw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9V2LvzO_3cnQLpUZ5O27sg.png" /></figure><h3>8. How can this approach help large enterprise applications?</h3><p>This is where I think the approach becomes particularly useful.</p><p>The current project uses three shards as a learning example. But the same idea can be extended to much larger automation suites.</p><p>Imagine an enterprise application with thousands of test cases covering login, customer management, subscriptions, payments, reporting, permissions and other business functions.</p><p>Running every test sequentially could take hours.</p><p>Instead, we can split the test suite into multiple shards and run them concurrently across separate Pods.</p><p>For example:</p><pre>2,000 automated tests<br>                    |<br>                    v<br>             Split into shards<br>                    |<br>        +-----------+-----------+<br>        |           |           |<br>        v           v           v<br>      Shard 1     Shard 2     Shard 3<br>        |           |           |<br>        v           v           v<br>      Pod 1       Pod 2       Pod 3<br>        |           |           |<br>        +-----------+-----------+<br>                    |<br>                    v<br>           Combine test results</pre><p>We can increase the number of shards and Pods as the test suite grows, provided the cluster has enough resources and the tests are suitable for parallel execution.</p><p>The objective is to reduce the time needed to get useful feedback from a large test suite.</p><p>However, more Pods do not automatically mean proportionally faster execution. Test dependencies, uneven test durations, shared test data, environment capacity and API limits can all affect the result.</p><h3>Use case 1: Faster regression testing</h3><p>Before releasing a new version of an enterprise application, the QA team may need to execute a large regression suite.</p><p>With distributed execution, the team can split the suite into smaller groups and run them at the same time.</p><p>This can help reduce feedback time and make it easier to fit regression testing into a release schedule.</p><h3>Use case 2: Testing different browsers</h3><p>Enterprise applications often need to support different browsers.</p><p>With Playwright, we can configure browser projects for Chromium, Firefox and WebKit. We can then distribute the browser-specific test executions across separate jobs or Pods.</p><p>For example, we could run a set of tests against all three browsers in parallel. If we have three browser targets and five shards, we could create up to 15 execution groups.</p><p>This is useful when the application has many UI workflows and cross-browser compatibility is important.</p><p>The framework and pipeline must be configured to assign the correct browser project to each execution.</p><h3>Use case 3: Testing different application versions</h3><p>Some enterprise applications need to support multiple versions or customer environments.</p><p>For example, a team may need to validate:</p><ul><li>The current production version.</li><li>A new release candidate.</li><li>A previous supported version.</li><li>A staging environment with upcoming changes.</li></ul><p>We can reuse the same Playwright framework and pass different base URLs and configuration values to each execution.</p><p>If we need to test two application versions across three browsers with five shards, that could create up to 30 execution groups. The pipeline can distribute these groups according to the available capacity.</p><p>Of course, the application versions must be deployed and accessible first. Kubernetes runs the tests; it does not automatically create or deploy all those application versions.</p><h3>Use case 4: Combining browser, version and regression coverage</h3><p>The real benefit comes when we combine these approaches.</p><p>Instead of maintaining separate test frameworks for each browser or application version, we can build a reusable framework and control the execution through configuration.</p><p>This makes it easier to extend coverage as the application grows.</p><p>The same approach can support:</p><ul><li>Large regression suites.</li><li>Cross-browser testing.</li><li>Multiple supported application versions.</li><li>Different test environments.</li><li>Parallel API and UI test execution.</li></ul><p>The important part is to design the test framework so that tests can run independently and safely in parallel.</p><h3>9. What needs to be designed correctly?</h3><p>Distributed test execution is not only about adding more Pods.</p><p>For a reliable enterprise setup, we also need to consider the following:</p><ul><li><strong>Test independence:</strong> Tests should not depend on another test running first unless that dependency is managed explicitly.</li><li><strong>Test data:</strong> Parallel tests must not accidentally update or delete the same data.</li><li><strong>Configuration:</strong> Each execution needs the correct application URL, browser and environment settings.</li><li><strong>Secrets:</strong> Credentials should be stored securely.</li><li><strong>Resources:</strong> CPU and memory limits must be appropriate for the workload.</li><li><strong>Reporting:</strong> Results from every shard should be collected and combined.</li><li><strong>Failure investigation:</strong> Logs, screenshots and traces should be available when a test fails.</li><li><strong>Concurrency limits:</strong> The cluster should not run more workloads than it can handle effectively.</li></ul><p>For example, if ten Pods all try to update the same customer record, the tests may interfere with each other. Increasing the number of Pods would not solve that problem.</p><p>We need to design the tests and test data correctly before scaling the execution.</p><h3>10. What did I learn from this project?</h3><p>This project helped me understand how different technologies can work together in a QA automation workflow.</p><p>Here are my main takeaways:</p><ul><li><strong>Playwright:</strong> Creating reusable UI and API tests and splitting the test suite using sharding.</li><li><strong>Docker:</strong> Packaging the test environment into a reusable image.</li><li><strong>GitHub Actions:</strong> Automating test execution, report merging and Docker image publishing.</li><li><strong>AWS EKS and Kubernetes:</strong> Running test workloads across multiple Pods.</li><li><strong>Reporting:</strong> Combining results so that the complete execution can be reviewed in one place.</li><li><strong>Troubleshooting:</strong> Inspecting Pod logs, configuration and resource usage when something goes wrong.</li></ul><p>I also learned that there is a difference between running tests in a CI pipeline and running them in Kubernetes.</p><p>In this project, GitHub Actions handles the automated CI tests and image publishing. I then start the EKS test execution manually through CloudShell.</p><p>The next step would be connecting these parts through a secure deployment workflow so that a successful CI run can trigger the Kubernetes Job automatically.</p><h3>Conclusion</h3><p>For me, this was a useful opportunity to go beyond writing Playwright test cases and explore how the test framework can be packaged, distributed and run in a cloud environment. I used existing demo websites and APIs so that I could focus on the automation infrastructure.</p><p>The current implementation uses three shards in GitHub Actions and three Pods in AWS EKS. But the same approach can be extended to larger test suites and more complex testing requirements.</p><p>With the right design, distributed execution can help enterprise teams run regression tests more efficiently, validate multiple browsers and test different application versions without maintaining a separate framework for every scenario.</p><p>There is still more to explore, especially automating the GitHub-to-EKS deployment and improving report collection. But this project has given me a practical understanding of how these technologies fit together.</p><p>If you are learning Playwright and want to explore Docker and Kubernetes for QA automation, feel free to check out the repository and try it yourself.</p><p><strong>GitHub repository:</strong> <a href="https://github.com/sheepankaj/playwrightdockerkubernetestesting-lab">https://github.com/sheepankaj/playwrightdockerkubernetestesting-lab</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mh80q2glTYB5xZ6UhJ5VBw.png" /></figure><p>Thanks for reading! See you in my next blog.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79e062dc27c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Load Testing using K6 with Playwright and Showing result in locally generated html report]]></title>
            <link>https://medium.com/@sheepankaj/load-testing-using-k6-with-playwright-and-showing-result-in-locally-generated-html-report-49ef1387df4d?source=rss-94140a0f703------2</link>
            <guid isPermaLink="false">https://medium.com/p/49ef1387df4d</guid>
            <category><![CDATA[k6]]></category>
            <category><![CDATA[performance-testing]]></category>
            <category><![CDATA[load-testing]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[automation-testing]]></category>
            <dc:creator><![CDATA[Pankaj Kumar Shee]]></dc:creator>
            <pubDate>Fri, 08 May 2026 17:15:09 GMT</pubDate>
            <atom:updated>2026-07-07T16:23:47.008Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi All, Welcome back to another blog of mine. This time I’ll share the performance testing using k6 tool. Let’s dive in.</p><p>As we know performance is a very important factor for today’s website to handle large responses. You can’t just ignore performance. Here I have used K6 tool to do my different performance tests such as smoke, load, stress and spike test. I generate a HTML report locally through a third party package and use this for pipeline too. For pipeline I use the Azure Pipeline to run my load/stress tests by selecting a specific test environment such as DEV/QA/UAT/Etc.</p><p><strong>Prerequisites:<br>1. </strong><a href="https://code.visualstudio.com/">VS code</a><br>2. NodeJs<br>3. yarn<br>4. K6 : <a href="https://k6.io/open-source/">https://k6.io/open-source/</a><br>5. Have <strong>knowledge and experience on performance testing </strong>with at least one language such as JavaScript. Here I used JavaScript<strong>.</strong></p><p><strong>K6 Load Testing Tool:</strong> It is an open-source performance testing tool and cloud service that makes load testing easy for developers and QA engineers. It is designed to help to test the performance and reliability of APIs, microservices, and websites</p><p><strong>Framework Structure:</strong><br>1. <strong>Project Name: DemoK6PerformanceTest</strong><br>1.1. scripts folder — having all scripts to run in Azure pipeline<br>1.2. testconfig folder — having all test types set up parameters<br>1.3. tests folder — having all performace tests files<br>1.4. utils folder — having all helper functions.<br>1.5. .env file — having all sectrets to use in the test<br>1.6. .gitignore file — having all files which are not commited to pipeline<br>1.7. build.yml — having all details to run in the pipeline<br>1.8. package.json — has all scripts to run tests<br>1.9. reports- having all locally generated html reports.<br>1.10. Using a 3rd party package to generate HTML report locally. Git Url: <a href="https://github.com/benc-uk/k6-reporter">https://github.com/benc-uk/k6-reporter</a><br>1.11: setup folder — having UI authentication test</p><p>Let’s dive into the real implementation:<br> Create a test file inside the tests folder and named as: k6demotest.js</p><pre>import { getJson } from &#39;../utils/httpHelper.js&#39;;<br>import { options } from &#39;../testconfig/loadconfig.js&#39;;<br>export { options };<br>import { group, check } from &#39;k6&#39;;<br>import { generatePerformanceDetailsSummary } from &#39;../utils/reportHelper.js&#39;;<br>import { exampleCarCommonEndpoint } from &#39;../testconfig/constants.js&#39;;<br><br>export default function () {<br> group(&#39;Car API Performance Test with filter by Region&#39;, () =&gt; {<br>  const data = getJsonResponseFromAPIRequest(exampleCarCommonEndpoint, { region: &#39;Asia&#39; }, {}, { name: &#39;ExampleCar_ByFilter_Region&#39; });<br><br>  check(data.res, {<br>   &#39;status for ExampleCar API Filter with Region test is 200&#39;: (r) =&gt; r.status === 200,<br>  });<br> });<br>}<br><br>export function handleSummary(data) {<br> return generatePerformanceDetailsSummary(data);<br>}</pre><p>We’ll discuss each components used in the above test file.<br>&gt;‘<strong>group</strong>’ is used from k6 to keep all same requests in the same group.<br>&gt;‘<strong>getJsonResponseFromAPIRequest</strong>’ is a function developed in the reportHelper.js file to build endpoint and get the response to validate later.<br>&gt;’<strong>check(data, res)</strong>’ is used to validate the status of the api response and and asserts the response status is 200; the pass-rate of that assertion becomes part of the perf-test report.<br>&gt;’<strong>handleSummary(data)</strong>’ is used to capture all k6 metrics and generate the HTML report locally. <strong>k6</strong> calls handleSummary(data) once at the end of a run.<br>&gt;’<strong>options</strong>’ is defined the entire test run by keeping stages (test types) and expected parameters of all tests configurations.</p><h3><strong>Constants for Base API URL and Common Endpoints:</strong></h3><p>Create a <strong>constants </strong>file inside the testconfig folder. This file has base_Api_Url and all common endpoints used in all tests. These values will be used in all tests and getJsonResponseFromAPIRequest().</p><pre>export const base_Api_Url = &#39;https://testdemo.${_ENV.testEnv}.examplek6.com&#39;;<br>export const exampleCarCommonEndpoint = &#39;/api/v1/CarToBuy/cars&#39;;j<br><br>Note: These above values are only example and no real website. You can replace your test website and commonEndpoints in the above.</pre><h3>Performance Test Parameters:</h3><p>Create another file named as <strong>stages.js</strong> inside the testconfig folder. This file has kept all test types values such as smoke, spike, load, and stress.</p><pre>export const stages = {<br> smoke: [<br>  { duration: &#39;5s&#39;, target: 5 },<br>  { duration: &#39;50s&#39;, target: 5 },<br>  { duration: &#39;5s&#39;, target: 0 },<br> ],<br> spike: [<br>  { duration: &#39;5s&#39;, target: 20 },<br>  { duration: &#39;5m&#39;, target: 20 },<br>  { duration: &#39;5s&#39;, target: 0 },<br> ],<br> load: [<br>  { duration: &#39;1m&#39;, target: 5 },<br>  { duration: &#39;3m&#39;, target: 15 },<br>  { duration: &#39;10m&#39;, target: 25 },<br>  { duration: &#39;4m&#39;, target: 15 },<br>  { duration: &#39;1m&#39;, target: 0 },<br> ],<br> stress: [<br>  { duration: &#39;1m&#39;, target: 5 },<br>  { duration: &#39;2m&#39;, target: 25 },<br>  { duration: &#39;6m&#39;, target: 50 },j<br>  { duration: &#39;2m&#39;, target: 50 },<br>  { duration: &#39;2m&#39;, target: 25 },<br>  { duration: &#39;1m&#39;, target: 0 },<br> ],<br>};</pre><p>Here target value refers to vertual users (VUs/Users) numbers and duration keeps the value of time a test runs with the set up target (users).</p><h3>Expected Performance Metrics:</h3><p>Create another new file as <strong>loadconfig.js</strong> inside the testconfig folder. This file has kept the expected metric parameters of each test and selected test mode. The test mode by default is setup as ‘smoke’.</p><pre>import { stages } from &#39;./stages.js&#39;;<br><br>const mode = __ENV.TEST_MODE || &#39;smoke&#39;;<br><br>if (!stages[mode]) {<br> throw new Error(`Unknown TEST_MODE &quot;${mode}&quot;. Use &quot;smoke&quot;, &quot;spike&quot;, &quot;load&quot;, or &quot;stress&quot;.`);<br>}<br><br>const selectedTestMode = stages[mode];<br><br>export const options = {<br> stages: selectedTestMode,<br> thresholds: {<br>  http_req_duration: [&#39;p(95)&lt;1500&#39;, &#39;avg&lt;2000&#39;], //average &amp; p95 assertions for load test<br>  http_req_failed: [&#39;rate&lt;0.05&#39;], //request failure assertion for stress test<br>  ...([&#39;load&#39;, &#39;stress&#39;, &#39;spike&#39;].includes(mode) ? { http_reqs: [&#39;rate&gt;10&#39;] } : {}), //throughput assertion for load/stress/spike tests<br> },<br> tags: {<br>  mytag: &#39;APIPerformanceValue&#39;,<br> },<br>};<br><br>console.log(`[K6] Running &#39;${mode}&#39; test with config:`, selectedTestMode);</pre><p>In the above mode storing the selected environment and default test mode values. options constant is keeping the selecte test mode and expected metric parameters of each test under thresholds{}, tags for filter.</p><ul><li><strong>http_req_duration: [&#39;p(95)&lt;1500&#39;, &#39;avg&lt;2000&#39;]</strong> — 95th-percentile latency stay under 1.5 seconds and mean latency stay under 2 seconds. Average alone hides tail behavior; p95 alone misses bulk regressions. Asserting both catches more.</li><li><strong>http_req_failed: [&#39;rate&lt;0.05&#39;]</strong> — fewer than 5% of requests return an error. This is the canary that tells you the system is <em>working</em>, not just fast.</li><li><strong>http_reqs: [&#39;rate&gt;10&#39;]</strong> — sustained throughput of at least 10 req/s. Without this, a &quot;passing&quot; run could mean k6 only managed two requests per minute and they were both fast. Throughput thresholds force the load to actually materialize.</li></ul><h3>Optional: Get Authorization Token from UI using Playwright Test:</h3><p>Create a file named as <strong>getAuthorizationTokenThroughPlaywrightUITest.spec.js</strong> inside setup folder. If your project needs authorization token for access, then you can use the below playwright test.</p><pre>import test, { test as setup, expect } from &#39;@playwright/test&#39;;<br>import * as fs from &#39;fs&#39;;<br>import * as path from &#39;path&#39;;<br>require(&#39;dotenv&#39;).config({ quiet: true });<br><br>test.setTimeout(60000);<br>setup(&#39;Generate Token&#39;, async ({ page }) =&gt; {<br> console.log(`Tests running on ${process.env.testEnv}. Generating token for ${process.env.loginId}`);<br> await page.goto(&#39;https://testdemo.qa.examplek6.com/signin&#39;);<br> const page1Promise = page.waitForEvent(&#39;popup&#39;);<br> await page.getByRole(&#39;button&#39;, { name: &#39;Client Sign in&#39; }).click();<br> const page1 = await page1Promise;<br> await page1.getByRole(&#39;textbox&#39;, { name: &#39;Username&#39; }).fill(process.env.loginId);<br> await page1.getByRole(&#39;textbox&#39;, { name: &#39;Password&#39; }).fill(process.env.loginPassword);<br> await page1.getByRole(&#39;button&#39;, { name: &#39;Sign in&#39; }).click();<br> await expect(page.getByRole(&#39;link&#39;, { name: &#39;Sign out&#39; })).toBeVisible();<br> await page.getByRole(&#39;link&#39;, { name: &#39;ExampleCars&#39; }).click();<br> await page.locator(&#39;a[href^=&quot;/car-details&quot;]&#39;).first().click(); // click on the first available link for token<br> await page.getByRole(&#39;button&#39;, { name: &#39;Try it &#39; }).click();<br> await page.getByLabel(&#39;Authorization Token flow:&#39;).selectOption(&#39;authorization_token (PKCE)&#39;);<br> await page.getByRole(&#39;button&#39;, { name: &#39;Toggle secrets&#39; }).click();<br> await expect(page.getByText(&#39;Bearer&#39;)).toBeVisible();<br> const token = await page.getByText(&#39;Bearer&#39;).textContent();<br> if (!token) throw new Error(&#39;Failed to retrieve Bearer token from UI.&#39;);<br> process.env.authToken = token?.split(&#39; &#39;)[1] ?? &#39;&#39;;<br> if (!process.env.CI) {<br>  const envFilePath = path.resolve(__dirname, &#39;..&#39;, &#39;.env&#39;);<br>  let envContent = fs.readFileSync(envFilePath, &#39;utf8&#39;);<br><br>  // Replace the existing authToken value<br>  envContent = envContent.replace(/authToken=.*(\r?\n|$)/g, `authToken=&#39;${process.env.authToken}&#39;$1`);<br><br>  // Write the updated content back to the .env file<br>  fs.writeFileSync(envFilePath, envContent);<br>  console.log(`.env file updated with new token.`);<br> }<br> await page.close();<br>});</pre><p>This is a <strong>Playwright “setup” test that exists for one job: log into the Example Car portal in a real browser and capture a fresh bearer token</strong> for k6 to use afterwards. <br><strong>Loads </strong><strong>.env</strong> with dotenv so loginId, loginPassword, and testEnv are available locally. In the pipeline, those same vars come from the Dev.Qa.Env variable group injected via build.yml.</p><h3>Helper Methods:</h3><p>Create a new file named as <strong>httpHelper.js </strong>inside the utils folder. This file is the project’s thin wrapper around k6’s built-in HTTP client. It exists so test files don’t have to repeat URL assembly, auth, header merging, and JSON parsing on every request.</p><pre>import http from &#39;k6/http&#39;;<br>import { base_Api_Url } from &#39;../testconfig/constants.js&#39;;<br><br>const Auth_Token = __ENV.authToken;<br>console.log(`Auth token being used: ${Auth_Token?.substring(0, 15)}`);<br><br>export const defaultHeaders = {<br> ...(Auth_Token &amp;&amp; { Authorization: `Bearer ${Auth_Token}` }),<br> &#39;Content-Type&#39;: &#39;application/json&#39;,<br>};<br><br>export function buildParams(paramsObj = {}) {<br> const entries = Object.entries(paramsObj);<br> if (entries.length === 0) return &#39;&#39;;<br><br> return &#39;?&#39; + entries.map(([key, value]) =&gt; `${key}=${encodeURIComponent(value)}`).join(&#39;&amp;&#39;);<br>}<br><br>/**<br> * Performs a GET request to the given path (relative to BASE_URL),<br> * validates the response status and JSON format.<br> *<br> * @param {string} endpoint - Relative path like &#39;/car&#39;<br> * @param {object} customHeaders - Optional headers<br> * @returns {object} - Parsed JSON response<br> */<br>export function getJson(endpoint, params = {}, customHeaders = {}, tags = {}) {<br> const url = `${base_Api_Url.replace(/\/$/, &#39;&#39;)}${endpoint}${buildParams(params)}`;<br><br> const mergedHeaders = { ...defaultHeaders, ...customHeaders };<br> const res = http.get(url, { headers: mergedHeaders, redirects: 4, tags: tags.name ? tags : { name: endpoint } });<br><br> let isJson = true;<br> let json = null;<br><br> try {<br>  json = JSON.parse(res.body);<br> } catch (error) {<br>  console.log(error);<br>  isJson = false;<br> }<br><br> return { res, isJson, json };<br>}</pre><p><strong>What it provides</strong></p><ol><li><strong>Auth bootstrapping</strong> : Reads __ENV.authToken once at module load and bakes it into a shared defaultHeaders object as Authorization: Bearer &lt;token&gt;, alongside Content-Type: application/json. The console.log prints the first 15 chars of the token so you can confirm at a glance which token a CI run was using, without leaking the whole secret. <strong>This is an additional capability shared here to utilise if you need an authorization token.</strong></li><li><strong>buildParams(paramsObj)</strong>: Turns { pageSize: 50, name: &#39;A &amp; B&#39; } into ?pageSize=50&amp;name=A%20%26%20B. URL-encodes values with encodeURIComponent, returns an empty string for an empty object so callers don&#39;t end up with a stray ?.</li><li><strong>getJson(endpoint, params, customHeaders, tags):</strong>The main entry point every test calls. It:</li></ol><ul><li>Joinsbase_Api_Url (from testconfig/constants.js) with the relative endpoint and built query string, stripping a trailing slash so you don&#39;t double up on /.</li><li>Merges defaultHeaders with any per-call overrides.</li><li>Issueshttp.get(url, { headers, redirects: 4, tags }). Thetags arg is the important k6 piece — passing{ name:&#39;<em>ExampleCar_ByFilter_Region</em>&#39; }groups all requests under that label in metrics/reports; if no name is given it falls back to tagging by raw endpoint.</li><li>Wraps JSON.parse(res.body) in try/catch so a non-JSON response logs an error and sets isJson = false instead of crashing the iteration.</li><li>Returns { res, isJson, json } — raw response for check(...) assertions, a parse-success boolean, and the parsed body when available.</li></ul><h3>Methods To Generate HTML Report Locally:</h3><p>Create a new file named as <strong>reportHelper.js</strong> inside utils folder. This is the project’s centralized end-of-run reporter.</p><pre>import { htmlReport } from &#39;https://raw.githubusercontent.com/benc-uk/k6-reporter/main/dist/bundle.js&#39;;<br>import { textSummary } from &#39;https://jslib.k6.io/k6-summary/0.0.1/index.js&#39;;<br><br>/**<br> * Returns a handleSummary-compatible object for HTML and console reports.<br> * @param {Object} data - k6 summary data object<br> * @param {string} testFilePath - Full __FILE__ path from the caller test<br> * @returns {Object} Summary outputs<br> */<br>export function generatePerformanceDetailsSummary(data) {<br> const testType = __ENV.K6_TEST_TYPE || &#39;smoke&#39;;<br> const testName = __ENV.TEST_NAME || &#39;unnamed&#39;;<br> const generateHtmlReport = __ENV.REPORT_HTML === &#39;true&#39;;<br><br> // Format current date &amp; time as YYYY-MM-DD HH:mm<br> const currentSystemDate = new Date();<br> const formattedDate =<br>  currentSystemDate.getFullYear() +<br>  &#39;-&#39; +<br>  String(currentSystemDate.getMonth() + 1).padStart(2, &#39;0&#39;) +<br>  &#39;-&#39; +<br>  String(currentSystemDate.getDate()).padStart(2, &#39;0&#39;) +<br>  &#39; &#39; +<br>  String(currentSystemDate.getHours()).padStart(2, &#39;0&#39;) +<br>  &#39;:&#39; +<br>  String(currentSystemDate.getMinutes()).padStart(2, &#39;0&#39;);<br><br> const outputs = {<br>  stdout: textSummary(data, { indent: &#39; &#39;, enableColors: true }),<br> };<br><br> if (generateHtmlReport) {<br>  const reportsDir = __ENV.RUN_ENV === &#39;docker&#39; ? &#39;/reports&#39; : &#39;./reports&#39;;<br>  const fileName = `${reportsDir}/${testType}_${testName}-summary.html`;<br>  outputs[fileName] = htmlReport(data, {<br>   title: `${testName}: ${formattedDate}`,<br>  });<br> }<br><br> return outputs;<br>}</pre><p><strong>What generatePerformanceDetailsSummary builds:</strong></p><ol><li><strong>Reads three env vars</strong> to drive output:</li></ol><ul><li>K6_TEST_TYPE (default smoke) — filename prefix.</li><li>TEST_NAME (default unnamed) — second filename segment and HTML report title.</li><li>REPORT_HTML — must be the literal string &#39;true&#39; to emit the HTML file.</li></ul><p><strong>2. Formats a timestamp</strong> as YYYY-MM-DD HH:mm for the HTML report title, using local time.<br>3. <strong>Always emits </strong><strong>stdout</strong> via textSummary(data, { indent: &#39; &#39;, enableColors: true }) from https://jslib.k6.io/k6-summary/0.0.1/index.js. That&#39;s the colored ASCII summary — checks pass-rate, latency percentiles, threshold ✓/✗ marks — that you see in your terminal at the end of every run.<br>4. <strong>Conditionally emits HTML</strong> when REPORT_HTML=true, using htmlReport(data, { title }) from benc-uk/k6-reporter. The output path is is /reports in Docker (RUN_ENV=docker) or ./reports locally — so the same code works whether the test is running in a container with a mounted volume or directly on a dev box. The report format name is &lt;reportsDir&gt;/&lt;K6_TEST_TYPE&gt;_&lt;TEST_NAME&gt;-summary.html.<br>It prints the summary to stdout <em>and</em> store the report file in this./reports/examplePerformanceTest-summary.html next to the test.</p><p><strong>Optional:</strong> Just create a file named as .env and add the below constant to run tests locally. These values will be used in all tests and you control your setup variables.</p><pre>testEnv=qa<br>loginId=&#39;performancetest@k6.com&#39;<br>loginPassword=&#39;123656789&#39;<br>authToken=&#39;eyJhb.............................DQ&#39;</pre><h3>PowerShell Script To Run in Pipeline:</h3><p>Create a new file named as <strong>run-test-pipeline-generate-htmlreport.ps1</strong> inside scripts folder. This file has all scripts to run tests in pipeline. I have kept separate scripts files to run tests in pipeline and locally.</p><pre>param (<br>    [string]$ScriptsDir = &quot;./tests&quot;,<br>    [string]$TestType = &quot;smoke&quot;,<br>    [string]$Environment = &quot;qa&quot;,<br>    [string]$TestsToRun = &quot;all&quot;<br>)<br><br># Step 1: Load .env variables<br>Write-Host &quot;`nLoading environment variables from .env...&quot; -ForegroundColor Cyan<br><br>Get-Content .env | ForEach-Object {<br>    if ($_ -match &#39;^\s*([^#][^=]+?)\s*=\s*(.*)\s*$&#39;) {<br>        $key = $matches[1].Trim()<br>        $value = $matches[2].Trim().Trim(&quot;&#39;&quot;).Trim(&#39;&quot;&#39;)<br>        [System.Environment]::SetEnvironmentVariable($key, $value, &quot;Process&quot;)<br>        Write-Host &quot;Loaded: $key&quot;<br>    }<br>}<br><br># Step 2: Validate token<br>$authToken = $env:authToken<br>if (-not $authToken) {<br>    Write-Host &quot;authToken not found in .env. Aborting.&quot; -ForegroundColor Red<br>    exit 1<br>}<br>else {<br>    Write-Host &quot;Token loaded: $($authToken.Substring(0, 15))...&quot; -ForegroundColor Green<br>}<br><br># Step 3: Check if k6 is installed<br>if (-not (Get-Command &quot;k6&quot; -ErrorAction SilentlyContinue)) {<br>    Write-Host &quot;K6 is not installed or not in PATH. Install from https://k6.io/docs/getting-started/installation/&quot; -ForegroundColor Red<br>    exit 1<br>}<br><br># Step 4: Create reports folder if it doesn&#39;t exist<br>if (-not (Test-Path -Path &quot;./reports&quot;)) {<br>    New-Item -ItemType Directory -Path &quot;./reports&quot; | Out-Null<br>}<br><br># Step 5: Locate test files<br>if ($TestsToRun -eq &quot;all&quot;) {<br>    Write-Host &quot;Running all test files...&quot; -ForegroundColor Yellow<br>    $testFiles = Get-ChildItem -Path $ScriptsDir -Filter *.test.js<br>} else {<br>    Write-Host &quot;Running tests starting with: $TestsToRun&quot; -ForegroundColor Yellow<br>    $testFiles = Get-ChildItem -Path $ScriptsDir -Filter &quot;$TestsToRun*.test.js&quot;<br>}<br><br>if ($testFiles.Count -eq 0) {<br>    Write-Host &quot;No test files found in $ScriptsDir matching filter: $TestsToRun&quot; -ForegroundColor Red<br>    exit 1<br>}<br><br># Step 6: Run all tests and generate html report in pipeline (published&gt;Artifacts)<br>foreach ($test in $testFiles) {<br>    $testName = $test.BaseName.Replace(&quot;.test&quot;, &quot;&quot;)<br>    $testPath = $test.FullName<br><br>    Write-Host &quot;`nRunning test: $testName&quot; -ForegroundColor Cyan<br><br>    # Enable HTML report generation for local run<br>    $env:REPORT_HTML = &quot;true&quot;<br><br>    # Pass all necessary environment variables to k6<br>    k6 run $testPath `<br>        -e authToken=$authToken `<br>        -e testEnv=$Environment `<br>        -e TEST_MODE=$TestType `<br>        -e K6_TEST_TYPE=$TestType `<br>        -e TEST_NAME=$testName `<br>        -e REPORT_HTML=$env:REPORT_HTML<br>}<br><br>Write-Host &quot;`nAll tests executed. Check the &#39;reports/&#39; folder for HTML reports.&quot; -ForegroundColor Green</pre><ol><li><strong>Takes four optional inputs.</strong> Where the tests live (./tests), which load profile to use (smoke/spike/load/stress), which environment (qa by default), and whether to run all tests or only files starting with a given prefix.</li><li><strong>Loads </strong><strong>.env.</strong> Reads the local .env file line by line and pushes each KEY=VALUE into the process environment so k6 can see them. This is how secrets like authToken get in without being hardcoded.</li><li><strong>Sanity-checks prerequisites.</strong> Aborts if authToken is missing, or if k6 isn&#39;t installed on the machine. Friendly error messages, non-zero exit codes — exactly what a pipeline needs to fail fast.</li><li><strong>Makes sure </strong><strong>./reports/ exists</strong> so the HTML files have somewhere to save.</li><li><strong>Finds the test files.</strong> Either every *.test.js in the tests folder, or only those matching the prefix you passed.</li><li><strong>Runs each test through k6</strong> in a loop, passing the env vars the test code expects:</li></ol><ul><li>authToken — for the Authorization: Bearer … header in httpHelper.js.</li><li>testEnv — which API environment to hit.</li><li>TEST_MODE — picks the stages profile in loadconfig.js.</li><li>K6_TEST_TYPE and TEST_NAME — used by reportHelper.js to name the HTML file.</li><li>REPORT_HTML=true — switches on HTML output in generatePerformanceDetailsSummary.</li></ul><p><strong>End result:</strong> for every test file, k6 prints the colored stdout summary <em>and</em> drops a per-test HTML report into ./reports/. In CI, that folder gets published as a pipeline artifact you can download and open in a browser.<br>So it’s the <strong>glue</strong> that connects the three pieces we already covered:</p><ul><li>loadconfig.js (which load profile)</li><li>httpHelper.js (auth + base URL)</li><li>reportHelper.js (HTML output)</li></ul><p>…into a single repeatable command instead of asking each engineer to remember the right k6 run -e ... invocation by hand.</p><p><strong><em>Command to run:</em></strong> <br>Add a line of code under scripts section inside <strong>package.json</strong> file to use the above code to run in the pipeline. Always run in powershell, not in bash terminal.</p><pre>&quot;scripts&quot;: {<br>  &quot;lint&quot;: &quot;eslint setup testconfig tests utils&quot;,<br>  &quot;prepare&quot;: &quot;husky&quot;,<br>  &quot;test:runpipeline&quot;: &quot;powershell -ExecutionPolicy Bypass -File ./scripts/run-test-pipeline-generate-htmlreport.ps1&quot;<br> },</pre><h3><strong>Build. YML File for Pipeline:</strong></h3><p>Now create the main puzzle file to run in pipeline named as build.yml inside the project. It is the <strong>Azure DevOps pipeline definition </strong>used to run all tests as a CI Job.</p><pre>parameters:<br>  - name: environment<br>    displayName: Target Environment<br>    type: string<br>    default: &#39;qa&#39;<br>    values:<br>      - &#39;dev&#39;<br>      - &#39;qa&#39;<br>      - &#39;uat&#39;<br><br>  - name: testMode<br>    displayName: Test Mode<br>    type: string<br>    default: &#39;smoke&#39;<br>    values:<br>      - &#39;smoke&#39;<br>      - &#39;spike&#39;<br>      - &#39;load&#39;<br>      - &#39;stress&#39;<br>  - name: testsToRun<br>    displayName: Select which test to run<br>    type: string<br>    default: &#39;all&#39;<br>    values:<br>      - &#39;all&#39;<br>      - &#39;exampleCar-filterByRegion&#39;<br><br>name: $(Date:yyyyMMdd)$(Rev:.r)-${{ parameters.environment }}-${{ parameters.testMode }}<br><br>jobs:<br>  - job: K6PerformanceTests<br>    pool:<br>      name: &#39;VMS - DEV - QA&#39;<br>    variables:<br>      - group: Dev.Qa.Env<br>    timeoutInMinutes: 300<br><br>    steps:<br>      - checkout: self<br><br>      - script: npm ci --ignore-scripts<br>        displayName: &#39;Install NPM Dependencies&#39;<br><br>      - script: npx playwright install --with-deps chromium<br>        displayName: &#39;Install Playwright Browsers&#39;<br>        retryCountOnTaskFailure: 10<br><br>    # Run Playwright test to generate token<br>      - script: |<br>          echo &quot;Running Playwright test to fetch auth token...&quot;<br>          npx playwright test setup/getAuthorizationTokenThroughPlaywrightUITest.spec.js<br>        displayName: &#39;Run Playwright to fetch token&#39;<br>        workingDirectory: $(System.DefaultWorkingDirectory)<br>        env:<br>          testEnv: ${{ parameters.environment }}<br>          loginId: $(loginId)<br>          loginPassword: $(loginPassword)<br><br>    # Install k6 binary (Linux agent)<br>      - script: |<br>          echo &quot;Downloading k6 v1.0.0-rc1 binary...&quot;<br>          curl -L https://github.com/grafana/k6/releases/download/v1.0.0-rc1/k6-v1.0.0-rc1-linux-amd64.tar.gz -o k6.tar.gz<br>          mkdir -p $HOME/k6bin<br>          tar -xzf k6.tar.gz -C $HOME/k6bin --strip-components=1<br>          echo &quot;##vso[task.prependpath]$HOME/k6bin&quot;<br>        displayName: &#39;Install k6 binary (v1.0.0-rc1)&#39;<br><br>    # Verify k6 works<br>      - script: |<br>          which k6<br>          k6 version<br>        displayName: &#39;Verify k6 installation&#39;<br><br>    # Run K6 Performance Tests (will use to update .env parameters generated above playwright UI test)<br>      - script: |<br>          if [ &quot;$(Build.SourceBranchName)&quot; == &quot;master&quot; ]; then<br>            export qa_teams_webhook=$(qa_teams_webhook)<br>          fi<br><br>          export testEnv=${{ parameters.environment }}<br> <br>          export loginId=$(loginId)<br>          export loginPassword=$(loginPassword)<br><br>          # Run your K6 PowerShell wrapper<br>          pwsh -NoLogo -NoProfile -File &quot;$(System.DefaultWorkingDirectory)/scripts/run-test-pipeline-generate-htmlreport.ps1&quot; -TestType &quot;${{ parameters.testMode }}&quot; -Environment &quot;${{ parameters.environment }}&quot; -TestsToRun &quot;${{ parameters.testsToRun }}&quot;<br>        displayName: &#39;Running Example Car K6 Performance Tests&#39;<br>        workingDirectory: $(System.DefaultWorkingDirectory)<br>        env:<br>          CI: &#39;true&#39;<br>          AZURE_SERVER_URL: $(System.CollectionUri)<br>          AZURE_PROJECT: $(System.TeamProject)<br>          AZURE_RUN_ID: $(Build.BuildId)<br><br>    # Publish HTML Report<br>      - task: PublishPipelineArtifact@1<br>        displayName: &#39;Publish K6 HTML Report&#39;<br>        inputs:<br>          targetPath: &#39;reports&#39;<br>          artifact: &#39;K6-Report-$(System.JobAttempt)&#39;<br>        continueOnError: true<br>        condition: succeededOrFailed()</pre><h3>Top half: pipeline inputs</h3><p>Three parameters that show up as dropdowns when you queue the pipeline manually:</p><ul><li><strong>environment</strong> — which API stack to hit (dev / qa / uat), default qa.</li><li><strong>testMode</strong> — load profile (smoke / spike / load / stress), default smoke. Same names as the stages.js keys.</li><li><strong>testsToRun</strong> — all, or a specific test (or family like exampleCar-filterByRegion) so a single run can target one endpoint instead of the whole suite.</li></ul><p>name: builds the run label like 20260508.1-aqua-smoke so you can tell at a glance what each historical run did.</p><h3>Bottom half: the steps</h3><p>One job (K6PerformanceTests) running on a self-hosted Linux agent pool (VMS - DEV - QA), with a 5-hour timeout and secrets pulled from the Dev.Qa.Env variable group. It does seven things in order:</p><ol><li><strong>checkout: self</strong> — clone the repo onto the agent.</li><li><strong>npm ci --ignore-scripts</strong> — install Node dependencies (Playwright lives there).</li><li><strong>npx playwright install --with-deps chromium</strong> — install the Chromium browser Playwright drives, with up to 10 retries because of that download flakes.</li><li><strong>Run a Playwright test to fetch the auth token.</strong> <strong>setup/getAuthorizationTokenThroughPlaywrightUITest.spec.js</strong> logs into the UI with loginId / loginPassword from the variable group and writes the resulting bearer token somewhere k6 can read (the .env file). This is how the pipeline gets a fresh, valid token without anyone hardcoding one.</li><li><strong>Install the k6 binary.</strong> Downloads k6 v1.0.0-rc1 from GitHub, untars it into $HOME/k6bin, and prepends that to PATH for the rest of the job.</li><li><strong>Verify k6</strong> with which k6 and k6 version — fails the job early if the previous step somehow didn&#39;t put it on PATH.</li><li><strong>Run the perf suite.</strong> Calls pwsh on the same PowerShell script we just looked at — scripts/run-test-pipeline-generate-htmlreport.ps1 — passing the three pipeline parameters straight through. Also exports a Teams webhook secret only on master, so notifications fire from real CI runs but not from feature branches.</li><li><strong>Publish the </strong><strong>reports/ folder as a pipeline artifact</strong> named K6-Report-&lt;attempt&gt;. condition: succeededOrFailed() means you still get the HTML reports even when thresholds fail and the job is red — which is exactly when you most want to see them.</li></ol><p>So build.yml is the <strong>outermost shell</strong> of the system — it grabs a fresh token, installs k6, runs the PowerShell wrapper with the user&#39;s chosen parameters, and saves the HTML reports as a downloadable artifact. Everything else is what runs <em>inside</em> it.</p><h3>Example Screenshots Of The Report:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R_TrjzhY1EV1-TqFIgv2EQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sxQiQzdFUuN7zUoXIZnJLg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nDcgoCDttJvngy3KD8oeAg.png" /></figure><p>Happy Testing………………………….</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49ef1387df4d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to download multiple files and validate through API response to make your test more stable in…]]></title>
            <link>https://medium.com/@sheepankaj/how-to-download-multiple-files-and-validate-through-api-response-to-make-your-test-more-stable-in-aae474d9bc26?source=rss-94140a0f703------2</link>
            <guid isPermaLink="false">https://medium.com/p/aae474d9bc26</guid>
            <category><![CDATA[automation-testing]]></category>
            <category><![CDATA[downloadfile]]></category>
            <category><![CDATA[playwright-test]]></category>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[software-testing]]></category>
            <dc:creator><![CDATA[Pankaj Kumar Shee]]></dc:creator>
            <pubDate>Tue, 12 Aug 2025 15:49:54 GMT</pubDate>
            <atom:updated>2025-08-12T15:49:54.178Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to download multiple files and validate through API response to make your test more stable in Playwright?</h3><p>Welcome to my blog, again we are going to talk about a solution with playwright testing framework. As I mentioned earlier, popularity of playwright is increasing each passing day. So, let’s find out the approach and solution.</p><p><strong>Thoughts on issue:</strong><br>I developed a simple solution for my test to download multiple pdf files by ticking the ‘Select All Checkbox’ button and click the ‘Download’ button, then validate each ‘check box’ turns to green tick. So, each checkbox turns green tick once the respective file was downloaded. In this process, it appears few times checkbox turning green tick takes time because of slowness, network issue, etc and because of this my test failed few times, that irritates me. So, I am looking for better solution to make it more stable, then I found the solution by validation the api response too for the same. It worked and my test is passing each time without compromising the scenario’s validation. That’s something satisfying.</p><p><strong>Codes:</strong><br>Putting whole solution inside the playwright test, you can separate the code based on your framework and reusability. Let’s create the test.</p><pre>import { test, expect } from &#39;@playwright/test&#39;;<br><br>test(&#39;Validate download all files by clicking select all checkbox button and click download button&#39;, async({page}) =&gt;{<br>    await page.goto(&#39;https://example.com/downloadfilespage&#39;);<br>    const downloadbutton = page.getByRole(&#39;button&#39;,{name:&#39;downloadButton&#39;});<br>    await expect(downloadbutton).toBeDisabled(); //This is confirmed donwload button disabled when page is load.<br>    await page.locator(&#39;paste your locator value for a button to enable - all checkbox button&#39;);<br>    await page.downloadbutton.click();<br><br>  //Now we&#39;ll do the api to verify all files are download and respective checkbox turns green tick after downloaded respectively.<br>     const baseRequestUrl = &#39;https://demoservices.qa.example.net/api/v1/testfiles/download/raw&#39;; //This is your enpoint url for download file, you can get this under browser&#39;s Element &gt; Network tab<br>     <br>  //Build the logic now<br>    let successfulCallCount = 0,<br>        failedCallCount = 0,<br>        failedRequestUrls = [];<br>    <br>  //Below will check the api status of 200 for each requestUrl of download file<br>    page.on(&#39;response&#39;, async (response) =&gt; {<br>       const url = response.url();<br>       if (url.startsWith(baseRequestURL)) {<br>            const status = response.status();<br>            if (status === 200) {<br>                 successfulCallCount++;<br>            } else {<br>               failedCallCount++;<br>               failedRequestUrls.push(url);<br>            }<br>         }<br>    });<br>  <br>    await page.waitForTimeout(1000); //wait for the download to start<br>    await expect(page.locator(&#39;paste your download spinner locator that started when download kicks atarted&#39;).toHaveCount(0, {timeout: 4000}); //wait for the download to finish<br>    <br>    //Below will show in the console when download is failed with respected requestUrl of download file.<br>    if(failedCallCount &gt; 0) {<br>       console.log(`✅ Passed: Expected All PDF Files Downloaded and Their Counts: ${successfulCallCount}`);<br>       console.log(`❌ Failed: Files uanble to download and their Counts: ${failedCallCount}`);<br>       failedRequestUrls.forEach((f) =&gt; console.log(`- ${f}`));<br>       expect(failedCallCount).toBe(0);<br>    }<br>});</pre><p>Now, you can see the above code how easily handles the download files with api response. My test became more stable after implementing the above solution.</p><p><strong><em>Doubts in your mind:</em></strong><br>You may have think why my developer team had not implemented the pop up option after downloading all files. I would say they have less time and the system they have built linked with other systems and backed services, so it’ll take them more time to implement the pop up option. But whatever solution they have built and sent to QA to test it soon. So, QA has put on pressure to test and approve it to release soon with working as per above. <br>As far as system is working as expected functionality, then it’s fit the business. So, I found the above solution for automation and It’s worked each time. Now you can try too in your system too if you have similar scenario. Happy Testing…..</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aae474d9bc26" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Comparison and Validation Tests between two databases for the same table]]></title>
            <link>https://medium.com/@sheepankaj/data-comparison-and-validation-tests-between-two-databases-for-the-same-table-7ee2b0f9fd25?source=rss-94140a0f703------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ee2b0f9fd25</guid>
            <category><![CDATA[quality-assurance]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[playwright-test]]></category>
            <category><![CDATA[automation-testing]]></category>
            <category><![CDATA[database-testing]]></category>
            <dc:creator><![CDATA[Pankaj Kumar Shee]]></dc:creator>
            <pubDate>Tue, 29 Apr 2025 16:53:23 GMT</pubDate>
            <atom:updated>2025-04-29T16:53:23.190Z</atom:updated>
            <content:encoded><![CDATA[<p>Data is king in modern days and correct data is liked ‘GOLD’. So, we need to validate the data too while testing to make the system working as expected with the correct data. So, It’s become very difficult to validate all data when data size is large and automation becomes handy in this case. You can do automation testing too for database with <strong>playwright </strong>framework and ‘<strong>mssql</strong>’ library. There are other tools too specifically developed to do database testing. But now you can do it with playwright too. I’ll show you the test in this blog how to config DBs connection and compare data and validate too exactly. Let’s dive in. <br><strong>Prerequisite:</strong><br> 1. VS Code<br> 2. NPM<br> 3. Playwright<br> 4. mssql library</p><h4>DB Connection with the help of mssql library in playwright:</h4><p>After set up and installing all required libraries for your project, create a new file and add the below details for database connection and sql query execution.<br>File Name: ‘sqlConnection.js =&gt; This has all methods for database connection and sql query execution as well as comparing data for each record between two databases’ tables respectively.</p><pre>const { expect } = require(&#39;@playwright/test&#39;);<br>const sql = require (&#39;mssql&#39;);<br><br>//This function establishes the database connection to respective database and execute sql query<br>const testDBConnectionAndExecuteSqlQuery = (query, databaseName) =&gt;{<br>      const dbConfig1 = {<br>            user:&#39;your username for the db&#39;,<br>            password: &#39;your password for the db&#39;,<br>            server: &#39;your server IP/Url&#39;,<br>            port: &#39;Your port value&#39;,<br>            databse: &#39;your database name&#39;,<br>            options: {<br>                encrypt: false,<br>                rowCollectionOnRequestCompletion: true,<br>                trustServerCertificate: true,<br>            },<br>          };<br><br>const dbConfig2 = {<br>            user:&#39;your username for the db&#39;,<br>            password: &#39;your password for the db&#39;,<br>            server: &#39;your server IP/Url&#39;,<br>            port: &#39;Your port value&#39;,<br>            databse: &#39;your database name&#39;,<br>            options: {<br>                encrypt: false,<br>                rowCollectionOnRequestCompletion: true,<br>                trustServerCertificate: true,<br>            },<br>          };<br><br>return new Promise((resolve, reject) =&gt;{ <br>        const dbConfig = dbName === &#39;your database name&#39; ? dbConfig1 : dbConfig2;<br>        sql.connect(dbConfig).then((connection) =&gt; {<br>          connection.query(query, (error, results) =&gt;{<br>            if(error) reject(error);<br>            else{<br>                connection.close();<br>                return resolve(results);<br>            }<br>        });<br>     });<br>  });<br>};<br><br>//This function compare and validate specified tables in two databases, if mismatches exist, then it&#39;ll show in the output<br>const compareAndValidateTablesInTwoDBs = (dataInDB1, dataInDB2, columnName, tableNameInDB1, tableNameinDB2, columnToIgnore=[]) =&gt; {<br>//This specifies the unicode Normalization form.  <br>const normalizeText = (text) =&gt; text?.toString().trim().normalize(&#39;NFC&#39;);<br>  let mismatchRecordsInDB2 = [];<br><br>for(let i=0; i&lt;dataInDB1.length; i++) {<br>    const recordInDB1 = dataInDB1[i];<br>    const recordInDB2 = dataInDB2[i];<br><br>    const specifiedColumnInDB2 = recordInDB2[columnName]¦¦ `Row Index: ${i})`;<br>    let recordMismatchData = false;<br>    <br>    for(const key of Object.keys(recordInDB1)){<br>      if (columnToIgnore.include(key)) continue;<br>      <br>        const recordOfSpecifiedTableInDB1 = normalizeText(recordInDB1[key]);<br>        const recordOfSpecifiedTableInDB2 = normalizeText(recordInDB2[key]);<br><br>       if (recordOfSpecifiedTableInDB1 !== recordOfSpecifiedTableInDB2) {<br>        recordMismatchData = true;<br>        console.log(`Mismatch in ${tableNameInDB2} for column &#39;${key}&#39; at ${columnName} row: ${specifiedColumnInDB2}`);<br>        console.log(`${tableNameInDB1} Data at row: &quot;${recordOfSpecifiedTableInDB1}&quot;`);<br>        console.log(`${tableNameInDB2} Data at row: &quot;${recordOfSpecifiedTableInDB2}&quot;`);<br>    }<br>    if(recordMismatchData) {<br>        mismatchRecordsInDB2.push({<br>          columnName: specifiedColumnInDB2,<br>          tableNameInDB1: JSON.stringify(recordInDB1),<br>          tableNameInDB2: JSON.stringify(recordInDB2),<br>          });<br>        }<br>    }<br>    if(mismatchRecordsInDB2.length === 0) {<br>      console.log(&#39;✅ All records in both tables are matching exactly.&#39;);<br>      }<br>  expect(mismatchRecordsInDB2.length, `Mismatch records found, please see the output`).toBe(0);<br>};<br>module.exports = { testDBConnectionAndExecuteSqlQuery, compareAndValidateTablesInTwoDBs };</pre><p>In the above below values represents:<br><strong>dataInDB1: </strong>Rows from 1st databse<br><strong>dataInDB2: </strong>Rows from 2nd database<br><strong>columnName:</strong> Specified column name<br><strong>tableNameInDB1:</strong> specified table name in 1st database<br><strong>tableNameinDB2:</strong> specified table name in 2nd databse<br><strong>columnToIgnore=[]:</strong> Specified column name for ignoring when comparing two tables because some column’s values are generated randomly in database when copying it.</p><h4>Automation Tests covering databases comparison and validation:</h4><p>Now we need to use these above function to use in our playwright test.j<br>&gt; Create a new file under tests folder and named it as databseTests.spec.js and add your database tests in this file.</p><pre>const {test, expect} = require(&#39;@playwright/test&#39;);<br>const {testDBConnectionAndExecuteSqlQuery, compareAndValidateTablesInTwoDBs} = require(&#39;path of your sqlConnection.js file&#39;);<br><br>test(`Validating xyz_Table records and counts in database1 against databse2`, async()=&gt;{<br>    const databaseName1=&#39;Your database1 name&#39;;<br>    const databaseName1=&#39;Your database2 name&#39;;<br>    const database1_xyz_TableName = &#39;database1 xyz_Table&#39;;<br>    const database2_xyz_TableName = &#39;database2 xyz_Table&#39;;<br><br>    const database1_xyz_Table_RecordCounts = await testDBConnectionAndExecuteSqlQuery(&quot;SELECT count(*) as totalRecords FROM [dbo].[TestTable] where Id&lt;= &#39;100&#39;;&quot;,&#39;databaseName1&#39;);<br>    const database2_xyz_Table_RecordCounts = await testDBConnectionAndExecuteSqlQuery(&quot;SELECT count(*) as totalRecords FROM [dbo].[TestTable]&quot;,&#39;databaseName2&#39;);<br>    const recordsetdatabase1_xyz_Table_RecordCounts = database1_xyz_Table_RecordCounts.recordset?.[0]?.totalRecords;<br>    const recordsetdatabase2_xyz_Table_RecordCounts = database2_xyz_Table_RecordCounts.recordset?.[0]?.totalRecords;<br>    <br>    console.log(`Total record counts in ${databaseName1}: `, recordsetdatabase1_xyz_Table_RecordCounts);<br>    console.log(`Total record counts in ${databaseName2}: `, recordsetdatabase2_xyz_Table_RecordCounts);<br>    //This will compare and validate the total records against the table in both database<br>    expect(recordsetdatabase2_xyz_Table_RecordCounts).toBe(recordsetdatabase1_xyz_Table_RecordCounts);<br>  <br>    const database1_xyz_Table_Records = await testDBConnectionAndExecuteSqlQuery(&quot;SELECT  * FROM [dbo].[TestTable] where Id&lt;= &#39;100&#39; order by Id desc;&quot;,&#39;databaseName1&#39;);<br>    const database2_xyz_Table_Records = await testDBConnectionAndExecuteSqlQuery(&quot;SELECT  * FROM [dbo].[TestTable] order by Id desc;&quot;,&#39;databaseName2&#39;);<br>    <br>    const recordset_database1_xyz_Table_Records = database1_xyz_Table_Records.recordset;<br>    const recordset_database2_xyz_Table_Records = database2_xyz_Table_Records.recordset;<br>    <br>    //This will compare the table in both database exactly and failed the test if there is any mismatch along with show the record where it is mismatched for debugging<br>    compareAndValidateTablesInTwoDBs(<br>      recordset_database1_xyz_Table_Records,<br>      recordset_database2_xyz_Table_Records,<br>      &#39;ColumnName that you can track the failed record in the table&#39;,<br>      database1_xyz_TableName,<br>      database2_xyz_TableName,<br>      &#39;ColumnName to ignore while comparing&#39;<br>    );<br>});</pre><p><strong>recordset</strong> in the above refers to a data structure that consists of a group of database records, and can either come from a base table or as the result of a query to the table.<br>Now run the test through terminal command:<br>&gt; npx playwright test<br>You can see your test will pass and fail if there is any mismatch between records with giving you the exact table record row where the mismatch data existing in which database too.<br>Your output look like this:<br><strong>Total record counts in databaseName1 database1 xyz_Table : 100 <br>Total record counts in databaseName2 database2 xyz_Table: 100 <br>✅ All data in both tables are matching exactly.</strong></p><p><strong>Conclusion:</strong></p><p>This way automation will give you confident that all data are matching exactly and have an assurance that system will behave as expected with correct data. Also, It will reduce time and cost to test a large set of data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ee2b0f9fd25" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Playwright: Type a value and Select the expected option from the Drop Down List]]></title>
            <link>https://medium.com/@sheepankaj/playwright-type-a-value-and-select-the-expected-option-from-the-drop-down-list-841da63812da?source=rss-94140a0f703------2</link>
            <guid isPermaLink="false">https://medium.com/p/841da63812da</guid>
            <category><![CDATA[automation-testing]]></category>
            <category><![CDATA[playwrights]]></category>
            <category><![CDATA[playwright-community]]></category>
            <category><![CDATA[dropdownlist]]></category>
            <category><![CDATA[automation-solution]]></category>
            <dc:creator><![CDATA[Pankaj Kumar Shee]]></dc:creator>
            <pubDate>Wed, 26 Mar 2025 18:42:33 GMT</pubDate>
            <atom:updated>2025-03-26T18:42:33.897Z</atom:updated>
            <content:encoded><![CDATA[<p>Playwright is a great framework and it’s popularity increasing day by day. Playwright is a modern testing framework that offers everything QA automation engineers look for, including a simple setup, built-in reporting, support for multiple languages, parallel execution, cross-browser testing, and it’s open-source.</p><p>Many time It happens when developing your automation test. You may have faced problems and taking lots of time to implement your logic as well as website becomes unstable and locators behave badly. One action is very common now a days in most websites. It’s selecting the expected option from a drop down list as you typing in a search field. Thanks to playwright it has a great inbuilt method to replicate the user’s typing action and that’s method is pressSequentially(). I’ll show you details in the below.</p><p>First find out the locators of the dropdown button. Then use the above pressSequentially() to type the value in the ddl field. As you are typing the value in the ddl field, you can see a drop down list appear with highlighting typed value. Now the real fun begins. Refers to the below code.</p><pre>this.ddlButton = page.locator(&#39;#ddl1&#39;);<br>await this.ddlButton.pressSequentially(&quot;Option1&quot;);<br>//await this.page.waitForTimeout(1000); for CI - use only if your website is slow in the pipeline and tests are faling because of slowness</pre><p>Now you get the locator value of the drop down list such as class and keep it in a constant, then wait for it. You can easily get the class locator from the element.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8qS7Bqv_EcQ3MbrRGYXbtA.png" /></figure><pre>const ddlList = page.locator(&#39;.Enter your class locator value&#39;);<br>await ddlList.waitFor();</pre><p>Once the drop down list appeared, then count all list values and keep it in a constant, use for loop to go through all list values and select your typed(expected) ddl list value from it.</p><pre>const ddlListCounts = await ddlList.locator(&quot;Enter your list locator value&quot;).count();<br>//Example for the above screenshot.<br>//const ddlCountryListCounts = await ddlList.locator(&quot;div&quot;).count(); -- This will get all country list values<br>for(let i = 0; i &lt; ddlListCounts; i++)<br>{ <br>  const expectedDDLValue = await ddlList.locator(&quot;Enter your list locator value/Same Locator in ddlListCounts&quot;).nth(i).textContent();<br>  if(expectedDDLValue === &quot;Your Typed/Searched Value&quot;)<br>      {<br>        await ddlList.locator(&quot;Enter your list locator value/Same Locator in ddlListCounts&quot;).nth(i).click();<br>        break;<br>      }<br>}</pre><p>As you selected your expected value in the ddl field, then you can continue to add other steps in your test as per requirements.</p><p>Here is the full code for reference:</p><pre>this.ddlButton = page.locator(&#39;Enter your locator value&#39;);<br><br>await this.ddlButton.pressSequentially(&quot;Enter you search value/expected value&quot;);<br>//await this.page.waitForTimeout(1000); for CI - use only if your website is slow in the pipeline and tests are faling because of slowness<br>const ddlList = page.locator(&#39;.Enter your class locator value&#39;);<br>await ddlList.waitFor();<br>const ddlListCounts = await ddlList.locator(&quot;Enter your list locator value&quot;).count();<br>//Example for the above screenshot.<br>//const ddlCountryListCounts = await ddlList.locator(&quot;div&quot;).count(); -- This will get all country list values<br>for(let i = 0; i &lt; ddlListCounts; i++)<br>{ <br>  const expectedDDLValue = await ddlList.locator(&quot;Enter your list locator value/Same Locator in ddlListCounts&quot;).nth(i).textContent();<br>  if(expectedDDLValue === &quot;Your Typed/Searched Value&quot;)<br>      {<br>        await ddlList.locator(&quot;Enter your list locator value/Same Locator in ddlListCounts&quot;).nth(i).click();<br>        break;<br>      }<br>}</pre><h3>Conclusion:</h3><p>I tried this solution in my own automation tests and it worked wonderfully. My tests are become more stable. My website is slow to load drop down list when I run my automation test and sometime it hangs the whole website. I used “waitForTimeout(1000)” to handle that in pipeline. After this my tests are stable and passed each time in the pipeline.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=841da63812da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Seamlessly Integrate Mailtrap with Playwright automation to Automate Access Code Retrieval from…]]></title>
            <link>https://medium.com/@sheepankaj/seamlessly-integrate-mailtrap-with-playwright-automation-to-automate-access-code-retrieval-from-dd28e0a9e184?source=rss-94140a0f703------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd28e0a9e184</guid>
            <category><![CDATA[mailtrap]]></category>
            <category><![CDATA[playwright-automation]]></category>
            <category><![CDATA[automation-testing]]></category>
            <category><![CDATA[playwright-community]]></category>
            <category><![CDATA[playwright-test]]></category>
            <dc:creator><![CDATA[Pankaj Kumar Shee]]></dc:creator>
            <pubDate>Fri, 14 Jun 2024 17:47:03 GMT</pubDate>
            <atom:updated>2024-06-14T17:47:03.909Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*b-GpoFauMZNvC66uOjgoBg.png" /></figure><h3>Seamlessly Integrate Mailtrap with Playwright automation to Automate Authenication Code Retrieval from the latest Email Subject</h3><p>Let’s start with what is mailtrap and playwright before jumping to details.</p><p><strong>Prerequisites:</strong></p><ol><li><a href="https://code.visualstudio.com/">VS code</a></li><li><a href="https://playwright.dev/">Playwright</a></li><li><a href="https://mailtrap.io/">Mailtrap</a></li><li><a href="https://axios-http.com/docs/intro">Axio</a></li><li>Have <strong>knowledge and experience on playwright automation</strong> with at least one language such as JavaScript, TypeScript, C#, Java and Python. Here I used <strong>Typescript.</strong></li></ol><p><strong>Mailtrap: </strong>It is an Email Delivery Platform to test, send and control email infrastructure in one place. You can create different inboxes as per project and take control of your testing workflows. It has API to help and integrate with your automation testing. It is free for certain use limits. Here is the link for mailtrap: <a href="https://mailtrap.io/">https://mailtrap.io/</a></p><p><strong>Mailtrap API document link</strong>: <a href="https://api-docs.mailtrap.io/docs/mailtrap-api-docs/5tjdeg9545058-mailtrap-api">https://api-docs.mailtrap.io/docs/mailtrap-api-docs/5tjdeg9545058-mailtrap-api</a></p><p><strong>Playwright Automation:</strong> It is an open-source automation library for browser testing and web scraping developed by Microsoft. Despite being relatively new, its popularity has surged rapidly, recently surpassing Cypress in monthly downloads. It supports cross-browser, cross-platform, and cross-language testing, making it a versatile tool for automation.</p><p>Key features include:</p><ul><li>Compatibility with all modern rendering engines: Chromium, WebKit, and Firefox.</li><li>Support for multiple programming languages: JavaScript, TypeScript, C#, Java, and Python.</li><li>Testing capabilities on Windows, Linux, and macOS, both locally and on CI, in headless or headed modes.</li><li>Built-in reporting features with options for screenshots and video recordings of tests.</li></ul><p>With these robust features, Playwright is a powerful choice for developers and testers seeking comprehensive and efficient automation solutions. Here is the link for Playwright for more.<a href="https://playwright.dev/">https://playwright.dev/</a></p><p><strong>Axio:</strong> It is a simple promise based HTTP client for the browser and node.js. Axios provides a simple to use library in a small package with a very extensible interface.</p><p>Let’s Jump to code without wasting any time:</p><p><strong>Create an EmailHelper class file</strong>, then write these below functions:</p><pre>Skeleton class of EmailHelper:<br><br>import axios from &#39;axios&#39;;<br>import * as data from &#39;../common/data/data.json&#39;;<br><br>export default class EmailHelper {<br>      private static readonly BASE_MailtrapURL = &quot;Enter your Base Url of Mailtrap (get it from Mailtrap setting)&quot;;<br>      private static readonly API_TOKEN = &quot;Enter your mailtrap API Token value&quot;;<br><br>  //method to get emailheader with respect to email subject and extract the authentication code from the email body<br>  public static async getAuthenticationCodeAsPerEmailSubject(expectedEmailSubject: string){<br>  };<br><br>  //method to get the latest email messageID from the mailtrap inbox.<br>  private static async getLatestEmailMessageId(){<br>  };<br><br>  //method to get the email header from the given account, inbox and latest email messageID<br>  private static async fetchEmailHeaders(){<br>  };<br><br>  //method to get email body from the given account, inbox and latest email messageID<br>  private static async fetchEmailBody(){<br>  };<br><br>  //method to retrieve authentication code from the email body<br>  private static extractAuthenticationCode(){<br>  };<br>}</pre><p>Let’s go one by one implementation of the above class:</p><p>Here is the details: Below function is the main function to use in your page class file, then in your test class file.</p><pre>public static async getAuthenticationCodeAsPerEmailSubject(expectedEmailSubject: string): Promise&lt;string&gt;{<br>        const latestRetrievedEmailMessageId = await this.getLatestEmailMessageId(data.accountId, data.inboxId);<br>        const emailHeaders = await this.fetchEmailHeaders(data.accountId, data.inboxId, latestRetrievedEmailMessageId);<br>        const emailSubject = emailHeaders.headers.subject;<br>        console.log(`Email subject matched as expected value: ${emailSubject}`);<br><br>        // Validate the email subject as expected email subject here<br>        if (emailSubject!== expectedEmailSubject) {<br>            throw new Error(`Email subject does not match as expected value: ${expectedEmailSubject}`);<br>        }<br><br>        const emailBody = await this.fetchEmailBody(data.accountId, data.inboxId, latestRetrievedEmailMessageId);<br>        console.log(`Email body: ${emailBody}`);<br><br>        // Retrieve the authentication code from the email body here<br>        const authentication = this.extractAuthenticationCode(emailBody);<br><br>        if (!authentication) {<br>            throw new Error(&#39;Authentication code not found in email body&#39;);<br>        }<br>        console.log(`Authentication code: ${authentication}`);<br><br>        return authentication;<br>  };</pre><p>In the above function the accountID, InboxID are stored in a data file and access it through importing the class. This function retrieves the latest email headers, validates the email subject against the expected email subject, extracts the authentication code from the email body, and returns the authentication code.</p><p><strong>Get the Latest Email MessageID:</strong></p><p>First you need to get the latest email messageID from the mailtrap inbox. Mailtrap is always displayed the latest email at top and that has message ID. This message ID has unique number each time for each email in an inbox. So, it’s difficult to get the email header directly through a straight single API.</p><pre>private static async getLatestEmailMessageId(accountId: number, inboxId: number): Promise&lt;number&gt; {<br>        const url = `${this.BASE_MailtrapURL}/accounts/${accountId}/inboxes/${inboxId}/messages`;<br>        const headers = {<br>            &#39;Accept&#39;: &#39;application/json&#39;,<br>            &#39;Api-Token&#39;: this.API_TOKEN<br>        };<br><br>        try {<br>            const response = await axios.get(url, { headers });<br>            const messages = response.data;<br><br>            // Sort by &#39;last_message_sent_at&#39; property<br>            const latestEmailMessage = messages.sort((a: { last_message_sent_at: string | number | Date; }, b: { last_message_sent_at: string | number | Date; }) =&gt; new Date(b.last_message_sent_at).getTime() - new Date(a.last_message_sent_at).getTime())[0];<br><br>            return latestEmailMessage.id;<br><br>        } catch (error) {<br>            console.error(`Error fetching messages: ${error}`);<br>            throw error;<br>        }<br>    };</pre><ol><li>The url variable is constructed using string interpolation, combining the BASE_MailtrapURL constant with the accountId and inboxId values.</li><li>The headers object is defined with two properties: Accept and Api-Token. These headers will be sent along with the HTTP request.</li><li>The code then uses axios, an HTTP client library, to send a GET request to the specified URL with the provided headers. The await keyword is used to wait for the response to be returned asynchronously.</li><li>If the request is successful, the response data is stored in the messages variable.</li><li>The code then sorts the messages array based on the &#39;last_message_sent_at&#39; property. The sort function takes a comparison function that compares the &#39;last_message_sent_at&#39; values of two messages and returns a negative, zero, or positive value depending on their order. This sorts the messages in descending order based on the timestamp of the last message sent.</li><li>Overall, this code fetches messages from a specified URL, sorts them based on the timestamp of the last message sent, and returns the ID of the latest Email message.</li></ol><p><strong>Fetch Email Headers from the latest Email:</strong></p><pre>private static async fetchEmailHeaders(accountId: number, inboxId: number, messageId: number): Promise&lt;any&gt;{<br>        const url = `${this.BASE_MailtrapURL}/accounts/${accountId}/inboxes/${inboxId}/messages/${messageId}/mail_headers`;<br>        const headers = {<br>            &#39;Accept&#39;: &#39;application/json&#39;,<br>            &#39;Api-Token&#39;: this.API_TOKEN<br>        };<br><br>        try {<br>            const response = await axios.get(url, { headers });<br>            return response.data;<br><br>        } catch (error) {<br>            console.error(`Error fetching mail headers: ${error}`);<br>            throw error;<br>        }<br>  };</pre><ol><li>Overall, this code fetches the email headers of the latest email message ID by making an API request to the Mailtrap API using the provided accountId, inboxId, and messageId. It handles both successful responses and errors that may occur during the API request.</li></ol><p><strong>Fetch the Email Body from the retrieved latest email header in the above function.</strong></p><pre>private static async fetchEmailBody(accountId: number, inboxId: number, messageId: number): Promise&lt;string&gt; {<br>        const url = `https://mailtrap.io/api/accounts/${accountId}/inboxes/${inboxId}/messages/${messageId}/body.txt`;<br>        const headers = {<br>            &#39;Accept&#39;: &#39;text/plain, application/json&#39;,<br>            &#39;Api-Token&#39;: this.API_TOKEN<br>        };<br><br>        try {<br>            const response = await axios.get(url, { headers });<br>            return response.data;<br><br>        } catch (error) {<br>            console.error(`Error fetching email body: ${error}`);<br>            throw error;<br>        }<br>  };</pre><p><strong>Extract the authentication code from the fetched email body:</strong></p><pre>private static extractAuthenticationCode(emailBody: string): string | null {<br>    const authenticationMatch = emailBody.match(/&lt;b&gt;(\d+)&lt;\/b&gt;/);<br>    return authenticationMatch ? authenticationMatch[1] : null;<br>  };</pre><ol><li>Inside the method, there is a regular expression pattern /&lt;b&gt;(\d+)&lt;\/b&gt;/ which is used to match a specific pattern in the emailBody string. This pattern looks for a sequence of digits enclosed in &lt;b&gt; and &lt;/b&gt; tags.</li><li>If a match is found, the method returns the first captured group from the match, which corresponds to the digits inside the &lt;b&gt; and &lt;/b&gt; tags. If no match is found, the method returns null.</li><li>In summary, this method extracts a specific authentication code from the emailBody string by searching for a pattern and returning the matched digits.</li></ol><p><strong>Page Class File: LoginPage</strong></p><p>Now Create a page class file name as LoginPage and create a method to retrieve the authentication code and enter it in the authentication code field of the login page.</p><pre>export default class LoginPage {<br><br>public async enterLoginDetailsAndAuthenticationCode(emailSubject: string){<br>    await this.page.goto(&quot;Enter your website Url&quot;);<br>    await this.testBase.assertPageTitle(&quot;Enter Title of your login page&quot;);<br>    await this.page.fill(&quot;Enter your username locator value&quot;,&quot;Enter your username value&quot;);<br>    await this.page.fill(&quot;Enter your password locator value&quot;,&quot;Enter your password value&quot;);<br>    await this.page.click(&quot;Enter your login button locator value&quot;);<br>    await this.testBase.assertPageTitle(&quot;Enter Title of your authentication code page&quot;);<br>    const authenticationCode = await EmailHelper.getAuthenticationCodeAsPerEmailSubject(emailSubject);<br>    await this.page.fill(&quot;Enter your authentication code locator value&quot;, authenticationCode);<br>    await this.page.click(&quot;Enter your signin button locator value&quot;);<br><br>  }; <br>}</pre><p><strong>Test Class File:</strong></p><pre>test(&#39;Basic Validation Login and Authentication Code Test&#39;, async ({ LoginPage }) =&gt; {<br><br>    await LoginPage.enterLoginDetailsAndAuthenticationCode(&quot;Enter your expected Email Subject&quot;);<br>    await landingPage.clickLogoutButton();<br><br>  });</pre><p>Here you can pass your expected email subject in the test itself, then code will take care to retrieve the authentication code from the mailtrap and help to login to the system.</p><p><strong>Conclusion:</strong></p><p>Hope this will help you on your automation testing if you are using mailtrap and playwright in your automation. Happy manual and automation testing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd28e0a9e184" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Handle Dynamic Xpath and ID Locator Values in Selenium!?]]></title>
            <link>https://medium.com/@sheepankaj/how-to-handle-dynamic-xpath-and-id-locator-values-in-selenium-e296ff5a36f2?source=rss-94140a0f703------2</link>
            <guid isPermaLink="false">https://medium.com/p/e296ff5a36f2</guid>
            <category><![CDATA[selenium]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[xpath]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[selenium-test-automation]]></category>
            <dc:creator><![CDATA[Pankaj Kumar Shee]]></dc:creator>
            <pubDate>Mon, 08 Jan 2024 23:13:04 GMT</pubDate>
            <atom:updated>2024-01-08T23:13:04.732Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>What is XPath in Selenium?</em></strong></p><p>XPath is an XML path used to navigate through the HTML structure of the web page. It is used to find any element in the web page using XML path expression. XPath can be used to find elements on the web page where there is no ID, Name, or Class locator available to find any element. The syntax for Xpath is such as:</p><blockquote><strong>Xpath=//tagname[@attribute=’value’]</strong></blockquote><p>Xpath is very useful in automation testing. You can use XPath to handle dynamic locator values.</p><h3><strong>How to use Xpath to handle dynamic locator values!</strong></h3><p>When you are working in automation testing and getting dynamic xpath locator value each time for the element you are looking for. It’s frustrating to work on it. However, there is a better solution for it. You can use some xpath syntax to get the dynamic locator values. <br><strong>Example of Dynamic Xpath locator values in the HTML Page:</strong></p><pre>&lt;tbody&gt;<br>&lt;tr&gt;<br>&lt;td style=&quot;style=&quot;vertical-align: top;&quot;&gt;<br> &lt;input id=&quot;202410Dynamic_XpathElement&quot; class=&quot;borderBox&quot; style=&quot;float: left; height: auto; border: 1px solid rgb(189, 191, 196);&quot;  <br>   type =&quot;text&quot; tabindex = &quot;...&quot;<br>&lt;/td&gt;<br>&lt;/tr&gt;<br>&lt;/tbody&gt;</pre><p>As you can see the id locator has a unique value that is ”202410Dynamic_XpathElement” but those numbers(202410) are changed dynamically each time. So, you can use that ‘id’ locator value to create a stable xpath and use it in your automation to develop your test methods. Here is the xpath locator value for the above dynamic ID locators such as:</p><pre>IWebElement ClickBtnElement = driver.FindElement(By.XPath(&quot;//*[contains(@id, &#39;Dynamic_XpathElement&#39;)]&quot;));<br>ClickBtnElement.Click();</pre><p>In the above xpath, you are passing the string value of the ‘id’ locator only inside contains square bracket. This will help you to create a stable xpath for the dynamic locator value of an element.</p><h3>How to create a custom ID locator to handle dynamic locator values!</h3><p>Many times when you are working in automation testing. You may face and see a dynamic ID locator value and it changes each time. However, you can handle this quite smoothly with the help of the getAttribute() method. Once you get the value from the <strong>getAttribute()</strong>, use it to prepare your custom ID locator and use it in your method. We can take the above ‘id’ locator value example. First, we need to get the whole locator value, then we need to pass it in a string. Once we get it we need to retrieve the number value only with the help of the Regex class. Now we can create the custom ID value by combining the retrieved number value and string value of the locator value.</p><pre>IWebElement attributeValue = driver.FindElement(By.XPath(&quot;//*[contains(@id, &#39;Dynamic_XpathElement&#39;)]&quot;),&quot;id&quot;);<br>string retrievedDynamicIDNumbervalueOnly = Regex.Replace(attributeValue,&quot;[^0-9]&quot;, &quot;&quot;);<br><br>//custom ID<br>IWebElement customIDLocator = driver.FindElement(By.Id($&quot;{retrievedDynamicIDNumbervalueOnly}Dynamic_XpathElement&quot;));<br>customIDLocator.Click();</pre><p>As you can see above you got your custom ID locator value. Now You can use it anywhere your method of the test class. It’ll make your automation more stable. Mostly, you’ll find these types of dynamic locator values in any legacy system where the mindset of automation testing is not included when developing the system as well as the company may not have a quality mindset. Hope these two solutions will help you to build your stable automation tests.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e296ff5a36f2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Selenium WebDriver?]]></title>
            <link>https://medium.com/@sheepankaj/what-is-selenium-webdriver-3f0837677ee8?source=rss-94140a0f703------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f0837677ee8</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[automation-testing]]></category>
            <category><![CDATA[selenium-webdriver]]></category>
            <dc:creator><![CDATA[Pankaj Kumar Shee]]></dc:creator>
            <pubDate>Sat, 12 Nov 2022 00:58:58 GMT</pubDate>
            <atom:updated>2022-11-12T00:58:58.429Z</atom:updated>
            <content:encoded><![CDATA[<p>Selenium WebDriver is a browser automation library or API having all interactive methods to interact with a browser. It helps to build an automation framework to execute cross-browser test cases. It is used to execute automation testing of web applications. It is open-source software released under the Apache License 2.0. It is supported by widely used languages such as C#, Java, JavaScript, Python, Ruby, PHP, Perl, etc. It runs on platforms like Windows, macOS, and Linux. Many browsers are supported by it such as Chrome, Edge, Firefox, IE, Opera, and Safari.</p><h4><strong>General Example to understand Selenium WebDriver:</strong></h4><p>Take the example of a TV remote control. The TV remote is Selenium WebDriver, TV is a browser, TV channels are web applications, and whatever actions you are executing through the TV remote are your methods of automation framework. So, when you are changing a TV channel through the tv remote on your television, then It’s exactly behaving as Selenium WebDriver executing cross-browser test cases by taking action commands from an automation framework.</p><h4>Automation Framework you can build with it:</h4><p>You can develop a robust, scalable automation testing framework with the Selenium WebDriver. You can wrap it to make understandable methods for your framework which are easier for all and robust too. You can implement many types of design patterns in order to make your framework more stable, scalable, and robust such as POM (Page Object Model), and Page Factory. Personally, my future interest is developing a framework in the mindset of POM with BDD aspects. Example: Unit Test will have a method that contains full action of behavior such as Login. The login method has all combined actions of login (enter a username, enter a password, click the login button and validate after login into the system successfully).<br>Recently, the latest Selenium WebDriver is released which is called “Selenium 4” and this has many advanced features for the modern testing automation framework. One example is there is no need to worry about browser version updates as these will take care by Selenium 4 automatically.</p><blockquote>Official Selenium link: <a href="https://www.selenium.dev/"><strong><em>https://www.selenium.dev/</em></strong></a><br>Official Selenium WebDriver Link: <a href="https://www.selenium.dev/documentation/webdriver/"><strong><em>https://www.selenium.dev/documentation/webdriver/</em></strong></a></blockquote><p>How did you like my post, let me know through comments. If you have any questions let me know through the comment. Have a good day. Please share, like and comment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f0837677ee8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>