<?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 Hirok Sarker on Medium]]></title>
        <description><![CDATA[Stories by Hirok Sarker on Medium]]></description>
        <link>https://medium.com/@hirok-sarker?source=rss-a3df8e53780e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*3vSbgmFcw4Rq0RHw.</url>
            <title>Stories by Hirok Sarker on Medium</title>
            <link>https://medium.com/@hirok-sarker?source=rss-a3df8e53780e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 00:41:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hirok-sarker/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[Automating the “Un-Automatable”: Lessons from a Complex POS App]]></title>
            <link>https://hirok-sarker.medium.com/automating-the-un-automatable-lessons-from-a-complex-pos-app-a7dc3de56f35?source=rss-a3df8e53780e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7dc3de56f35</guid>
            <dc:creator><![CDATA[Hirok Sarker]]></dc:creator>
            <pubDate>Mon, 16 Feb 2026 07:51:36 GMT</pubDate>
            <atom:updated>2026-02-16T09:24:54.727Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k4ZHnZkUn7h8bZaGb9pErg.png" /><figcaption>AI-generated illustration showing a modern AI-assisted automation workflow.</figcaption></figure><p><em>How a Flutter-based point-of-sale app with zero automation support became a fully automated test suite — and what every QA engineer can take away from the journey.</em></p><p>If you’ve spent any time in QA, you’ve heard some version of this. Maybe you’ve even said it yourself. And honestly? It’s never true — but it’s never <em>easily</em> false either. The gap between “can’t be automated” and “fully automated” is where the real engineering happens.</p><p>This is the story of that gap. Specifically, it’s the story of building a production-grade automation framework for a <strong>Flutter-based Android POS application</strong> — an app running on POS terminals, handheld devices, and emulators — that was never designed with test automation in mind. No test IDs. No accessibility hooks. Dynamic rendering. Custom widgets. Hardware-dependent flows.</p><p>Whether you’re a seasoned QA lead who’s seen frameworks come and go, a mid-level engineer looking to level up your automation game, or someone just starting out and wondering where to begin — there’s something here for you.</p><h3>The App: What We Were Dealing With</h3><p>The application is a <strong>commercial point-of-sale system</strong> — the kind used across service industries. It runs on:</p><ul><li><strong>POS terminals</strong> — large tablet-style devices mounted at service counters</li><li><strong>Handheld devices</strong> — mobile devices carried by floor staff</li><li><strong>Kiosk mode</strong> — customer self-service ordering</li></ul><p>The flows aren’t simple “tap, type, verify” scenarios. A single end-to-end test might involve logging in with merchant credentials, entering a secure access PIN, navigating to settings to configure device connectivity, switching to self-service mode, selecting menu items with modifiers and options, proceeding through checkout with tip, signature, and payment, switching back to staff mode, verifying the order, and then opening a tab, editing it, closing it, adding a gratuity, and printing a receipt.</p><p>That’s not a unit test. That’s an entire business day compressed into a 3-minute script.</p><p>And the app? It’s built in <strong>Flutter</strong>.</p><p>If you’ve automated Flutter apps before, you know the pain. If you haven’t — keep reading.</p><h3>The Solution — the tech stack which became the problem solver</h3><p>Let’s address the elephant in the room. If you search for Appium tutorials, guides, or conference talks, the overwhelming majority use <strong>Java</strong> or <strong>Python</strong>. Those are the “default” Appium languages. Most teams reach for them without a second thought.</p><p>This project went a different route: <strong>TypeScript + WebdriverIO 9 + Appium 3</strong>.</p><p>Why? A few reasons worth considering, especially if you’re choosing a stack for a new project:</p><p><strong>TypeScript gives you type safety without the ceremony.</strong> Java’s verbosity is well-known. Python’s flexibility is great until a typo in a string selector silently breaks a test at 2 AM. TypeScript catches entire categories of errors at compile time while still feeling lightweight. When your page objects and flow configs are typed, your IDE becomes a co-pilot — autocomplete, refactoring, and inline errors save real hours every week.</p><p><strong>WebdriverIO is built for modern async workflows.</strong> Mobile automation is inherently asynchronous — waiting for elements, waiting for screens to transition, waiting for network calls. WebdriverIO’s async-first API makes this natural rather than fighting callback hell or wrapping everything in explicit waits. Its plugin ecosystem (Allure reporting, device services, custom commands) is mature and well-maintained.</p><p><strong>The JavaScript/TypeScript ecosystem is massive.</strong> Need to pipe MJPEG streams through ffmpeg? There’s a Node.js spawn API for that. Need to parse JSON config files? Native. Need to run parallel processes? Built-in. You’re never far from a solution.</p><p><strong>One language across the stack.</strong> If your frontend team writes TypeScript (and in 2025–2026, many do), your QA automation is in the same language. That lowers the barrier for developers to contribute to tests and for QA engineers to understand the app’s source code.</p><p>This isn’t to say Java and Python are wrong choices — they have larger Appium communities and more Stack Overflow answers. But if you’re starting fresh or evaluating your options, WebdriverIO + TypeScript deserves a serious look. It proved itself on one of the hardest automation targets imaginable.</p><h3>Challenge #1: Flutter and the Locator Problem</h3><p>Flutter doesn’t render native Android views. It draws pixels directly on a canvas. From the perspective of Android’s accessibility layer (which UiAutomator2 relies on), a Flutter app can look like a single opaque blob.</p><p><strong>What the element tree often looked like:</strong></p><pre>android.view.View<br>  └── android.view.View<br>      └── android.view.View<br>          └── android.view.View  ← Every widget. Same class. No IDs.</pre><p>No resource-id. No meaningful content-desc. Just nested, identical views.</p><p><strong>How it was solved:</strong></p><p>The app’s Flutter rendering did expose <em>some</em> accessibility information — but inconsistently. Menu items had content-desc attributes. Some buttons had accessibility labels. Others had nothing.</p><p>The answer was a <strong>multi-strategy locator system:</strong></p><pre>// Strategy 1: UiAutomator2 with descriptionContains (handles newlines in Flutter)<br>const menuItem = await $(`android=new UiSelector().descriptionContains(&quot;${itemName}&quot;)`);</pre><pre>// Strategy 2: Resource ID where available<br>const loginBtn = await $(`android=new UiSelector().resourceId(&quot;btn_sign_in&quot;)`);</pre><pre>// Strategy 3: Class name + instance index (last resort)<br>const pinField = await $(`android=new UiSelector().className(&quot;android.widget.EditText&quot;).instance(0)`);</pre><pre>// Strategy 4: UiScrollable for off-screen elements<br>const hiddenItem = await $(<br>  `android=new UiScrollable(new UiSelector().scrollable(true))` +<br>  `.scrollIntoView(new UiSelector().descriptionContains(&quot;${itemName}&quot;))`<br>);</pre><p><strong>The takeaway for every experience level:</strong> There is no single locator strategy that works for non-automation-friendly apps. If you’re early in your career, resist the temptation to find “the one correct way” to locate elements. Build a toolbox, not a tool. If you’re a senior engineer, bake this multi-strategy approach into your framework from day one — it saves enormous refactoring later.</p><h3>Challenge #2: Scrolling That Doesn’t Scroll</h3><p>Standard Appium scroll commands failed on several screens. The POS settings page used a custom Flutter scroll container that didn’t respond to UiAutomator2’s scrollIntoView.</p><p><strong>What failed:</strong></p><pre>// This did absolutely nothing on the settings page<br>await $(&#39;android=new UiScrollable(new UiSelector().scrollable(true)).scrollForward()&#39;);</pre><p><strong>Why it failed:</strong> UiAutomator2’s scrollIntoView works by looking for a native ScrollView or RecyclerView in the Android view hierarchy and dispatching scroll events to it. But Flutter doesn&#39;t use native scroll containers — it renders everything on its own canvas. So from UiAutomator2&#39;s perspective, there&#39;s nothing scrollable to scroll. The command fires, finds no valid scroll target, and silently does nothing.</p><p><strong>What worked instead:</strong></p><p>Instead of relying on the framework to figure out <em>what</em> to scroll, we bypassed the abstraction entirely and told the device exactly <em>where</em> and <em>how</em> to swipe — using percentage-based coordinates calibrated per device type:</p><pre>async deviceSettingsScrollGesture() {<br>  await driver.execute(&#39;mobile: swipeGesture&#39;, {<br>    left: Math.round(width * 0.789),<br>    top: Math.round(height * 0.784),<br>    width: Math.round(width * 0.015),<br>    height: Math.round(height * 0.518),<br>    direction: &#39;up&#39;,<br>    percent: 0.75,<br>  });<br>}</pre><p><strong>Why this works and why it matters:</strong></p><p>The mobile: swipeGesture command operates at the <strong>touch input level</strong>, not the widget level. It doesn&#39;t need to find a scrollable container in the accessibility tree — it simply simulates a finger swiping across a screen region. Flutter ignores UiAutomator2&#39;s scroll commands, but it still listens for raw touch input from the Android OS. That&#39;s the gap this exploits.</p><p>The percentages (width * 0.789, height * 0.784, etc.) make the gesture <strong>resolution-independent</strong>. Hardcoded pixels would break on a different screen size. Percentages scale — 78.9% from the left edge hits the same UI region whether the screen is 1080p or 1440p. Each device type gets its own calibrated gesture because a 10-inch POS terminal and a 6-inch handheld place the scrollable area in physically different spots.</p><p>Is this elegant? No. Is it the right engineering choice? Absolutely. When the standard API offers zero support, dropping one abstraction level — from widget-based scrolling to raw touch — isn’t a hack. It’s the correct response to a framework limitation. Knowing when to step outside an abstraction, and doing so in a controlled way, is what separates a test scripter from a test engineer.</p><h3>Challenge #3: Android 11+ Broke Screen Recordings</h3><p>Video recordings of every test run are invaluable for debugging. On real devices, Appium’s Media Projection recording worked fine. But on emulators running Android 11+, scoped storage restrictions blocked saving recordings.</p><p><strong>The workaround — a dual-mode recording system:</strong></p><pre>if (isEmulator) {<br>  // MJPEG stream from UiAutomator2 → ffmpeg → MP4<br>  const mjpegUrl = `http://localhost:${mjpegPort}/stream.mjpeg`;<br>  ffmpegProcess = spawn(ffmpegPath, [&#39;-i&#39;, mjpegUrl, &#39;-t&#39;, &#39;300&#39;, outputPath]);<br>} else {<br>  // Media Projection for real devices<br>  await driver.execute(&#39;mobile: startMediaProjectionRecording&#39;, { ... });<br>}</pre><p>Auto-detection of emulator vs. physical device, with every recording attached to the Allure report. When a test fails at 2 AM in CI, you can watch exactly what happened.</p><p>This is the kind of infrastructure that separates hobby automation from production automation. If you’re building a framework meant to last, invest in observability early.</p><h3>Challenge #4: Race Conditions and the Accidental Double-Tap</h3><p>Mobile apps have transition animations. Automated tests are fast. Sometimes too fast — a button gets tapped twice before the next screen loads, causing cascading failures.</p><p><strong>The solution — </strong><strong>safeClick:</strong></p><pre>const lastClickMap = new Map&lt;string, number&gt;();</pre><pre>export async function safeClick(element: WebdriverIO.Element, actionKey: string) {<br>  const now = Date.now();<br>  const lastClick = lastClickMap.get(actionKey) || 0;</pre><pre>  if (now - lastClick &lt; 500) {<br>    return; // Skip — too soon after last click<br>  }</pre><pre>  lastClickMap.set(actionKey, now);<br>  await element.click();<br>}</pre><p>Less than 20 lines. Eliminated an entire category of flaky failures. <strong>The best automation utilities are usually tiny.</strong> New engineers: don’t overcomplicate things. A small, well-placed guard can save weeks of debugging.</p><h3>Challenge #5: One Framework, Three Device Types</h3><p>A POS terminal, a handheld phone, and an Android emulator walk into a test suite. They have different screen sizes, different capabilities, different MJPEG ports, and different timing requirements.</p><p><strong>The architecture that handled it:</strong></p><pre>Test Spec<br>  └── FlowRunner (orchestrates steps via flags)<br>       ├── AuthFlow → LoginPage<br>       ├── PinEntryFlow → PinPage<br>       ├── OrderFlow → MenuPage → ItemOptionsPage → CartPage<br>       ├── SelfServiceFlow → SelfServicePage → CheckoutPage<br>       └── ConfigFlow → SettingsPage</pre><p>Each test spec uses <strong>presets</strong> — predefined flag combinations:</p><pre>await FlowRunner.runSelfServiceFlow(PRESET_FULL);<br>await FlowRunner.runHandheldFlow(PRESET_LOGIN_AND_ORDER);<br>await FlowRunner.runOrderFlow({ ...PRESET_ORDER, skipLogin: true });</pre><p>This Flow Runner pattern produced 17+ test specs from a small set of reusable flows and page objects. When the checkout screen changed, one page object got updated instead of seventeen tests.</p><p>For mid-level engineers looking to graduate from writing individual test scripts to designing frameworks: this is the leap. Think in flows and compositions, not individual tests.</p><h3>Challenge #6: Parallel Execution on Physical Devices</h3><p>Running POS and handheld tests simultaneously on two different physical devices connected to the same machine required careful isolation:</p><pre>capabilities: [<br>  { ...posCapabilities, &#39;wdio:maxInstances&#39;: 1, specs: PARALLEL_SPECS.pos },<br>  { ...handheldCapabilities, &#39;wdio:maxInstances&#39;: 1, specs: PARALLEL_SPECS.handheld },<br>]</pre><p>Each device gets its own MJPEG port (POS: 7810, Handheld: 7811), and device type is resolved at runtime from session capabilities:</p><pre>const deviceName = driver.capabilities[&#39;appium:deviceName&#39;];<br>globalThis.__DEVICE_TYPE__ = resolveDeviceTypeFromName(deviceName);</pre><p>Parallel execution is where automation frameworks earn their keep. Getting this right is non-trivial but the time savings compound fast.</p><h3>Challenge #7: CI/CD on Slow Emulators</h3><p>Emulators in CI are slower than local machines. Tests that passed locally failed in CI due to timeouts.</p><p><strong>The solution — configurable wait multipliers:</strong></p><pre>CI=true WAIT_APP_READY_TIMEOUT=90000 WAIT_MULTIPLIER=2 npm run test:handheld</pre><p>Every wait in the framework scales:</p><pre>export async function waitShort(ms: number = 1000) {<br>  const multiplier = parseFloat(process.env.WAIT_MULTIPLIER || &#39;1&#39;);<br>  await driver.pause(ms * multiplier);<br>}</pre><p>This turned CI from a flake factory into a reliable gate. If you’re dealing with CI flakiness, look at environment-aware timing before blaming the tests themselves.</p><h3>The Architecture That Emerged</h3><pre>┌──────────────────────────────────────────────────────────┐<br>│                      Test Specs (17+)                    │<br>│   self-service-flow │ mobile-order │ login │ checkout... │<br>├──────────────────────────────────────────────────────────┤<br>│                FlowRunner + Presets                       │<br>│     Flag-based orchestration │ Step screenshot capture    │<br>├──────────────────────────────────────────────────────────┤<br>│                   Business Flows (8)                     │<br>│   AuthFlow │ OrderFlow │ SelfServiceFlow │ ConfigFlow... │<br>├──────────────────────────────────────────────────────────┤<br>│                 Page Objects (14)                         │<br>│   LoginPage │ MenuPage │ CartPage │ CheckoutPage │ ...   │<br>├──────────────────────────────────────────────────────────┤<br>│                    Utilities Layer                        │<br>│   smartWait │ safeClick │ screenRecording │ stepCapture   │<br>├──────────────────────────────────────────────────────────┤<br>│              WebdriverIO 9 + Appium 3                    │<br>│         UiAutomator2 │ MJPEG │ Allure Reporter           │<br>├──────────────────────────────────────────────────────────┤<br>│              Android Devices / Emulators                  │<br>│         POS Terminal │ Handheld │ Emulator                │<br>└──────────────────────────────────────────────────────────┘</pre><p><strong>Tech stack:</strong> TypeScript, WebdriverIO 9, Appium 3, UiAutomator2, Mocha, Allure, ffmpeg, GitHub Actions, parallel execution across device types.</p><h3>Advice That Scales With Your Career</h3><h3>If You’re Just Starting Out</h3><p><strong>Start with “Why,” not “How.”</strong> Don’t begin by learning Selenium or Appium. Start by understanding why a test exists. What business risk does it mitigate? What user journey does it protect? The best automation engineers think like QA first and coders second.</p><p><strong>Learn one stack deeply.</strong> Web? Playwright or Cypress. Mobile? Appium + WebdriverIO. API? Supertest or REST Assured. Don’t try to learn everything simultaneously. Master one. The concepts transfer.</p><p><strong>Page Object Model is not optional.</strong> Every serious automation project uses some form of POM — not because it’s trendy, but because apps change and your tests need to survive those changes. One page object update vs. seventeen test fixes. The math is simple.</p><h3>If You’re Mid-Level and Ready to Level Up</h3><p><strong>Embrace flaky tests as teachers.</strong> A flaky test isn’t a nuisance. It’s a symptom. Every flaky test you debug will teach you something about timing, app state management, environment differences, or the app itself. Don’t disable them. Fix them. They’re telling you something important.</p><p><strong>Think in architecture, not scripts.</strong> The leap from “writing tests” to “designing frameworks” is the biggest career accelerator in QA automation. Study the Flow Runner pattern above. Think about how your tests compose. Design for change.</p><p><strong>Version control your test data.</strong> Credentials, test scenarios, flow configurations — all in JSON or YAML, all overridable via environment variables. No committed secrets. No “works on my machine.”</p><h3>If You’ve Been Doing This for Years</h3><p><strong>Challenge the defaults.</strong> The Appium ecosystem is dominated by Java and Python. That doesn’t make them the right choice for every project. TypeScript + WebdriverIO brought type safety, a modern async model, and ecosystem breadth that paid dividends on this project. Evaluate your tools; don’t just inherit them.</p><p><strong>Invest in observability.</strong> Screen recordings on every test run. Screenshots on every step. Allure reports with full traceability. When you’re debugging a failure from three time zones away, this infrastructure is the difference between a 5-minute fix and a 5-hour investigation.</p><h3>The AI Advantage</h3><p>Regardless of experience level, 2025–2026 brings tools that dramatically accelerate automation work.</p><p><strong>AI-assisted element inspection</strong> is a game-changer. This project integrated Appium MCP (Model Context Protocol) — an AI server that connects directly to Appium sessions. Instead of manually crawling the element tree, you ask for the checkout button and get the locator strategy, element properties, and reliability assessment. What used to take 15 minutes of clicking through Appium Inspector now takes seconds.</p><p><strong>AI-assisted test generation</strong> works well when you have defined page objects and flows. Describe the scenario you want, and the scaffolding appears. You still review and validate, but the assembly is instant.</p><p><strong>AI-assisted debugging</strong> turns cryptic UiAutomator2 errors into actionable guidance. Paste the error with the page source XML and get a real answer instead of scrolling through Stack Overflow threads from 2019.</p><p><strong>But here’s the critical caveat:</strong> AI accelerates learning. It doesn’t replace it. You still need to understand <em>why</em> a locator strategy works, <em>why</em> a wait is necessary, <em>why</em> parallel execution requires isolated state. Use AI as a pair programming partner, not a substitute for understanding.</p><h3>The Mindset That Matters</h3><p>Three traits separate the engineers who succeed at hard automation problems:</p><p><strong>Stubbornness.</strong> When standard scrolling fails, you record gestures. When Media Projection breaks on emulators, you pipe MJPEG through ffmpeg. You find a way.</p><p><strong>Humility.</strong> You accept that your first approach probably won’t work. You read the docs. You ask for help. You learn from the community. You share your failures publicly because someone out there is stuck on the exact same problem.</p><p><strong>Empathy.</strong> You remember that tests exist to protect users. Every automated flow represents a real person trying to place an order, pay a bill, or close out their shift. That’s what keeps you going when UiAutomator2 throws its 47th StaleElementReferenceError of the day.</p><h3>What’s Next</h3><p>The framework continues to evolve — visual regression testing for Flutter’s canvas-rendered UI, API trace integration with mitmproxy, deeper AI integration for self-healing locators, and cross-platform expansion to iOS.</p><p>But the foundation is solid. Seventeen test specs. Fourteen page objects. Eight business flows. Three device types. One framework.</p><p>It started with someone saying, “This app can’t be automated.”</p><p>It always does.</p><p><em>If you’re working on automating a difficult app and want to compare notes, the comments are open. The best solutions in this field come from shared experience.</em></p><p><em>Tech stack: TypeScript · WebdriverIO 9 · Appium 3 · UiAutomator2 · Mocha · Allure · ffmpeg · GitHub Actions · Appium MCP</em></p><h3>A Note of Thanks</h3><p>No framework is built in isolation.<br>Huge thanks to the team that made this possible — especially <strong>Ashik bhai</strong>, whose thorough code reviews sharpened every part of the framework and caught details the rest of us missed. Special thanks to <strong>Sabab bhai</strong> (<a href="https://www.linkedin.com/in/basabab/">https://www.linkedin.com/in/basabab/</a>) for the thoughtful review and valuable feedback. Good automation is a team sport, and this framework reflects the strength of a great team behind it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7dc3de56f35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Robust API Testing Framework with TypeScript, Mocha and Supertest]]></title>
            <link>https://hirok-sarker.medium.com/building-a-robust-api-testing-framework-with-typescript-mocha-and-supertest-6dbe23e7dacd?source=rss-a3df8e53780e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6dbe23e7dacd</guid>
            <dc:creator><![CDATA[Hirok Sarker]]></dc:creator>
            <pubDate>Sun, 27 Apr 2025 17:34:43 GMT</pubDate>
            <atom:updated>2025-04-27T17:34:43.028Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SIu3U22w90lB8AaLoiChsw.png" /><figcaption>Learn how to build a robust API testing framework using TypeScript, Mocha, and Supertest — ensuring reliability, scalability, and speed in your development workflow.<br> Image generated by ChatGPT</figcaption></figure><p><em>From a Single Test to a Scalable Architecture</em></p><h3>Introduction</h3><p>Most QA approach API testing by either cloning an existing framework or following a step-by-step tutorial. While this gets us up and running quickly, we often don’t fully understand why the framework is structured the way it is. It becomes a black box of code we simply copy and paste.</p><p>In this guide, I’ll take a different approach. We’ll build a robust API testing framework from scratch using TypeScript and Supertest. Starting with a single test file, we’ll gradually refactor it into a professional, scalable framework. You’ll understand exactly why each piece exists and how it fits into the bigger picture.</p><h3>Prerequisites</h3><p>Before we dive in, you should have:</p><ul><li>Basic understanding of RESTful <a href="https://github.com/hiroksarker/api-testing-framework.git">APIs</a></li><li>Familiarity with TypeScript</li><li>Node.js installed on your machine</li></ul><h3>Part 1: Project Setup</h3><p>Let’s start with setting up our project. Create a new folder and initialize it:</p><pre>mkdir -p api-testing-framework/src/{api,config,models,utils,__tests__}<br>cd api-testing-framework</pre><p>Now, let’s install the necessary dependencies:</p><pre>npm install --save-dev typescript ts-node mocha chai @types/mocha @types/chai<br>npm install --save-dev supertest @types/supertest zod dotenv</pre><p>Create a tsconfig.json file for TypeScript configuration</p><pre>{<br>    &quot;compilerOptions&quot;: {<br>      &quot;target&quot;: &quot;es2016&quot;,<br>      &quot;module&quot;: &quot;commonjs&quot;,<br>      &quot;esModuleInterop&quot;: true,<br>      &quot;forceConsistentCasingInFileNames&quot;: true,<br>      &quot;strict&quot;: true,<br>      &quot;skipLibCheck&quot;: true,<br>      &quot;outDir&quot;: &quot;./dist&quot;,<br>      &quot;rootDir&quot;: &quot;./src&quot;,<br>      &quot;types&quot;: [&quot;node&quot;, &quot;mocha&quot;, &quot;chai&quot;]<br>    },<br>    &quot;include&quot;: [&quot;src/**/*&quot;],<br>    &quot;exclude&quot;: [&quot;node_modules&quot;]<br>  }</pre><p>Update your package.json with the test script:</p><pre> &quot;scripts&quot;: {<br>      &quot;test&quot;: &quot;mocha --require ts-node/register &#39;src/**/*.test.ts&#39;&quot;,<br>      &quot;test:watch&quot;: &quot;mocha --require ts-node/register --watch --watch-files src/ &#39;src/**/*.test.ts&#39;&quot;<br> }</pre><h3>Part 2: Creating a Simple Test</h3><p>Now, let’s write our first API test. We’ll use <a href="https://jsonplaceholder.typicode.com/">JSONPlaceholder</a>, a free fake online REST API for testing.</p><p>Create a folder structure:</p><pre>src/<br>  __tests__/<br>    user-api.test.ts</pre><p>Here’s our initial test:</p><pre>// src/__tests__/user-api.test.ts<br>import request from &#39;supertest&#39;;<br><br>const API_BASE_URL = &#39;https://jsonplaceholder.typicode.com&#39;;<br>describe(&#39;User API&#39;, () =&gt; {<br>  it(&#39;should return a list of users&#39;, async () =&gt; {<br>    // Send a GET request to the /users endpoint<br>    const response = await request(API_BASE_URL)<br>      .get(&#39;/users&#39;)<br>      .expect(200);<br>    <br>    // Assertions<br>    expect(Array.isArray(response.body)).toBe(true);<br>    expect(response.body.length).toBeGreaterThan(0);<br>    expect(response.body[0]).toHaveProperty(&#39;name&#39;);<br>    expect(response.body[0]).toHaveProperty(&#39;email&#39;);<br>  });<br>});</pre><pre>npm test</pre><p>If everything is set up correctly, you should see a passing test.</p><h3>Part 3: Intentional Failure Demonstration</h3><p>Let’s see what happens when a test fails. I’ll change one of the assertions to something that will fail:</p><pre>// Intentionally make this fail<br>expect(response.body.length).toBeGreaterThan(100);</pre><p>When we run the test again, we’ll see a detailed error message showing:</p><ul><li>What we expected (greater than 100)</li><li>What we actually got (probably 10)</li><li>The exact line that failed</li></ul><p>This kind of feedback is crucial for debugging test failures. Let’s revert that change and continue.</p><h3>Part 4: Moving API Calls to Helpers</h3><p>Now, let’s make our code more maintainable by moving the API call to a helper function:</p><p>Create the following folder structure:</p><pre>src/<br>  api/<br>    user-api.ts<br>  __tests__/<br>    user-api.test.ts</pre><p>In the user-api.ts file:</p><pre>// src/api/user-api.ts<br>import request from &#39;supertest&#39;;<br><br>const API_BASE_URL = &#39;https://jsonplaceholder.typicode.com&#39;;<br>export async function getUsers() {<br>  const response = await request(API_BASE_URL)<br>    .get(&#39;/users&#39;);<br>  <br>  return response;<br>}</pre><p>Now update our test:</p><pre>// src/__tests__/user-api.test.ts<br>import { getUsers } from &#39;../api/user-api&#39;;<br><br>describe(&#39;User API&#39;, () =&gt; {<br>  it(&#39;should return a list of users&#39;, async () =&gt; {<br>    const response = await getUsers();<br>    const users: User[] = response.body;<br>    <br>    expect(response.status).to.equal(200);<br>    expect(users).to.be.an(&#39;array&#39;);<br>    expect(users.length).to.be.greaterThan(0);<br>    expect(users[0]).to.have.property(&#39;name&#39;);<br>    expect(users[0]).to.have.property(&#39;email&#39;);<br>    expect(users[0].company).to.have.property(&#39;name&#39;);<br>  });<br>});</pre><p>Let’s run the test again to make sure it still passes:</p><pre>npm test</pre><h3>Part 5: Adding TypeScript Models</h3><p>Let’s add TypeScript interfaces to model our user data. This gives us type safety and auto-completion:</p><p>Create a new folder structure:</p><pre>src/<br>  api/<br>    user-api.ts<br>  models/<br>    user.model.ts<br>  __tests__/<br>    user-api.test.ts</pre><p>Define the User interface:</p><pre>// src/models/user.model.ts<br>export const UserSchema = z.object({<br>  id: z.number(),<br>  name: z.string(),<br>  username: z.string(),<br>  email: z.string().email(),<br>  address: z.object({<br>    street: z.string(),<br>    suite: z.string(),<br>    city: z.string(),<br>    zipcode: z.string(),<br>    geo: z.object({<br>      lat: z.string(),<br>      lng: z.string(),<br>    }),<br>  }),<br>  phone: z.string(),<br>  website: z.string(),<br>  company: z.object({<br>    name: z.string(),<br>    catchPhrase: z.string(),<br>    bs: z.string(),<br>  }),<br>});</pre><p>Update the user-api.ts file to use this interface:</p><pre>// src/api/user-api.ts<br>import { apiContext } from &#39;./api-context&#39;;<br>import { User, UserSchema } from &#39;../models/user.model&#39;;<br>import { Logger } from &#39;../utils/logger&#39;;<br>import { ResponseValidator } from &#39;../utils/response-validator&#39;;<br><br>export async function getUsers() {<br>  try {<br>    Logger.info(&#39;Fetching all users&#39;);<br>    const response = await apiContext.get(&#39;/users&#39;);<br>    <br>    // Validate response against our schema<br>    const validatedData = ResponseValidator.validateArray(response.body, UserSchema);<br>    Logger.info(`Retrieved ${validatedData.length} users`);<br>    <br>    return {<br>      ...response,<br>      body: validatedData<br>    };<br>  } catch (error) {<br>    Logger.error(&#39;Error fetching users&#39;, error);<br>    throw error;<br>  }<br>}</pre><p>And update our test:</p><pre>// src/__tests__/user-api.test.ts<br>import { expect } from &#39;chai&#39;;<br>import { getUsers, getUserById, createUser, updateUser, deleteUser } from &#39;../api/user-api&#39;;<br>import { User } from &#39;../models/user.model&#39;;<br>import { TestData } from &#39;../utils/test-data&#39;;<br>import { setupTestHooks } from &#39;./setup&#39;;<br><br>// Setup test hooks<br>setupTestHooks();<br><br>describe(&#39;User API&#39;, () =&gt; {<br>  it(&#39;should return a list of users&#39;, async () =&gt; {<br>    const response = await getUsers();<br>    const users: User[] = response.body;<br>    <br>    expect(response.status).to.equal(200);<br>    expect(users).to.be.an(&#39;array&#39;);<br>    expect(users.length).to.be.greaterThan(0);<br>    expect(users[0]).to.have.property(&#39;name&#39;);<br>    expect(users[0]).to.have.property(&#39;email&#39;);<br>    expect(users[0].company).to.have.property(&#39;name&#39;);<br>  });<br>});</pre><p>The benefit here is that our IDE will now provide auto-completion for user properties, reducing errors and making tests easier to write.</p><h3>Part 6: Centralizing API Context and Configuration</h3><p>Let’s centralize our configuration to make it easier to manage:</p><pre>src/<br>  api/<br>    api-context.ts<br>    user-api.ts<br>  config/<br>    api-config.ts<br>  models/<br>    user.model.ts<br>  __tests__/<br>    user-api.test.ts</pre><p>First, create an API configuration file:</p><pre>// src/config/api-config.ts<br>import { EnvConfig } from &#39;./env-config&#39;;<br><br>export const ApiConfig = {<br>  baseUrl: EnvConfig.baseUrl,<br>  timeoutMs: EnvConfig.timeoutMs,<br>  defaultHeaders: EnvConfig.defaultHeaders<br>};</pre><p>Next, create an API context to manage request handling:</p><pre>// src/api/api-context.ts<br>import request from &#39;supertest&#39;;<br>import { ApiConfig } from &#39;../config/api-config&#39;;<br>import { Logger } from &#39;../utils/logger&#39;;<br><br>export class ApiContext {<br>  private baseUrl: string;<br>  private defaultHeaders: Record&lt;string, string&gt;;<br><br>  constructor() {<br>    this.baseUrl = ApiConfig.baseUrl;<br>    this.defaultHeaders = ApiConfig.defaultHeaders;<br>    Logger.debug(&#39;API Context initialized&#39;, { baseUrl: this.baseUrl });<br>  }<br><br>  async get(endpoint: string, headers: Record&lt;string, string&gt; = {}) {<br>    const mergedHeaders = { ...this.defaultHeaders, ...headers };<br>    const url = `${this.baseUrl}${endpoint}`;<br>    <br>    // Log request details<br>    Logger.logRequest(&#39;GET&#39;, url, mergedHeaders);<br>    <br>    const startTime = Date.now();<br>    let response;<br>    try {<br>      response = await request(this.baseUrl)<br>        .get(endpoint)<br>        .set(mergedHeaders)<br>        .timeout(ApiConfig.timeoutMs);<br>      <br>      const duration = Date.now() - startTime;<br>      Logger.logResponse(response.status, response.headers, response.body, duration);<br>      <br>      return response;<br>    } catch (error) {<br>      Logger.logError(error);<br>      throw error;<br>    }<br>  }<br><br>  async post(endpoint: string, body: any, headers: Record&lt;string, string&gt; = {}) {<br>    const mergedHeaders = { ...this.defaultHeaders, ...headers };<br>    const url = `${this.baseUrl}${endpoint}`;<br>    <br>    // Log request details<br>    Logger.logRequest(&#39;POST&#39;, url, mergedHeaders, body);<br>    <br>    const startTime = Date.now();<br>    let response;<br>    try {<br>      response = await request(this.baseUrl)<br>        .post(endpoint)<br>        .send(body)<br>        .set(mergedHeaders)<br>        .timeout(ApiConfig.timeoutMs);<br>      <br>      const duration = Date.now() - startTime;<br>      Logger.logResponse(response.status, response.headers, response.body, duration);<br>      <br>      return response;<br>    } catch (error) {<br>      Logger.logError(error);<br>      throw error;<br>    }<br>  }<br>}<br><br>export const apiContext = new ApiContext();</pre><p>Now, update the user-api.ts to use this context:</p><pre>// src/api/user-api.ts<br>import { apiContext } from &#39;./api-context&#39;;<br>import { User, UserSchema, UsersSchema } from &#39;../models/user.model&#39;;<br>import { Logger } from &#39;../utils/logger&#39;;<br>import { ResponseValidator } from &#39;../utils/response-validator&#39;;<br><br>export async function getUsers() {<br>  try {<br>    Logger.info(&#39;Fetching all users&#39;);<br>    const response = await apiContext.get(&#39;/users&#39;);<br>    <br>    // Validate response against our schema<br>    const validatedData = ResponseValidator.validateArray(response.body, UserSchema);<br>    Logger.info(`Retrieved ${validatedData.length} users`);<br>    <br>    return {<br>      ...response,<br>      body: validatedData<br>    };<br>  } catch (error) {<br>    Logger.error(&#39;Error fetching users&#39;, error);<br>    throw error;<br>  }<br>}<br><br>export async function getUserById(id: number) {<br>  try {<br>    Logger.info(`Fetching user with ID: ${id}`);<br>    const response = await apiContext.get(`/users/${id}`);<br>    <br>    // Validate response against our schema<br>    const validatedData = ResponseValidator.validate(response.body, UserSchema);<br>    Logger.info(`Retrieved user: ${validatedData.name}`);<br>    <br>    return {<br>      ...response,<br>      body: validatedData<br>    };<br>  } catch (error) {<br>    Logger.error(`Error fetching user with ID: ${id}`, error);<br>    throw error;<br>  }<br>}</pre><p>Our test remains largely unchanged:</p><pre>// src/__tests__/user-api.test.ts<br>import { getUsers, getUserById } from &#39;../api/user-api&#39;;<br>import { User } from &#39;../models/user.model&#39;;<br><br><br>describe(&#39;User API&#39;, () =&gt; {<br>  it(&#39;should return a list of users&#39;, async () =&gt; {<br>    const response = await getUsers();<br>    const users: User[] = response.body;<br>    <br>    expect(response.status).toBe(200);<br>    expect(Array.isArray(users)).toBe(true);<br>    expect(users.length).toBeGreaterThan(0);<br>    expect(users[0].name).toBeDefined();<br>  });<br>  it(&#39;should return a single user by ID&#39;, async () =&gt; {<br>    const response = await getUserById(1);<br>    const user: User = response.body;<br>    <br>    expect(response.status).to.equal(200);<br>    expect(user.id).to.equal(1);<br>    expect(user).to.have.property(&#39;name&#39;);<br>    expect(user).to.have.property(&#39;email&#39;);<br>    expect(user.company).to.have.property(&#39;name&#39;);<br>  });<br>});</pre><p>This centralization makes it much easier to:</p><ul><li>Change the base URL when switching environments</li><li>Add authentication tokens</li><li>Handle common error cases</li><li>Add logging or other cross-cutting concerns</li></ul><h3>Part 7: Adding Runtime Validation with Zod</h3><p>Let’s add runtime validation to ensure API responses match our expected schema:</p><p>First, install Zod if you haven’t already:</p><pre>npm install --save-dev zod</pre><p>Now, let’s update our user model to use Zod:</p><pre>// src/models/user.model.ts<br>import { z } from &#39;zod&#39;;<br><br>// Define the schema<br>export const UserSchema = z.object({<br>  id: z.number(),<br>  name: z.string(),<br>  username: z.string(),<br>  email: z.string().email(),<br>  address: z.object({<br>    street: z.string(),<br>    suite: z.string(),<br>    city: z.string(),<br>    zipcode: z.string(),<br>    geo: z.object({<br>      lat: z.string(),<br>      lng: z.string(),<br>    }),<br>  }),<br>  phone: z.string(),<br>  website: z.string(),<br>  company: z.object({<br>    name: z.string(),<br>    catchPhrase: z.string(),<br>    bs: z.string(),<br>  }),<br>});<br><br>// Extract the TypeScript type from the schema<br>export type User = z.infer&lt;typeof UserSchema&gt;;<br><br>// Array of users schema<br>export const UsersSchema = z.array(UserSchema);</pre><p>Update our API handler to validate responses against these schemas:</p><pre>// src/api/user-api.ts<br>import { apiContext } from &#39;./api-context&#39;;<br>import { User, UserSchema, UsersSchema } from &#39;../models/user.model&#39;;<br>import { Logger } from &#39;../utils/logger&#39;;<br>import { ResponseValidator } from &#39;../utils/response-validator&#39;;<br><br>export async function getUsers() {<br>  try {<br>    Logger.info(&#39;Fetching all users&#39;);<br>    const response = await apiContext.get(&#39;/users&#39;);<br>    <br>    // Validate response against our schema<br>    const validatedData = ResponseValidator.validateArray(response.body, UserSchema);<br>    Logger.info(`Retrieved ${validatedData.length} users`);<br>    <br>    return {<br>      ...response,<br>      body: validatedData<br>    };<br>  } catch (error) {<br>    Logger.error(&#39;Error fetching users&#39;, error);<br>    throw error;<br>  }<br>}<br><br>export async function getUserById(id: number) {<br>  try {<br>    Logger.info(`Fetching user with ID: ${id}`);<br>    const response = await apiContext.get(`/users/${id}`);<br>    <br>    // Validate response against our schema<br>    const validatedData = ResponseValidator.validate(response.body, UserSchema);<br>    Logger.info(`Retrieved user: ${validatedData.name}`);<br>    <br>    return {<br>      ...response,<br>      body: validatedData<br>    };<br>  } catch (error) {<br>    Logger.error(`Error fetching user with ID: ${id}`, error);<br>    throw error;<br>  }<br>}</pre><p>With this change, if the API returns data that doesn’t match our expected schema, the test will fail with a detailed error message showing exactly what’s wrong.</p><h3>Part 8: Creating Utilities for Reusability</h3><p>Let’s add utilities for common operations:</p><pre>src/<br>  api/<br>    api-context.ts<br>    user-api.ts<br>  config/<br>    api-config.ts<br>  models/<br>    user.model.ts<br>  utils/<br>    logger.ts<br>    test-data.ts<br>    response-validator.ts<br>  __tests__/<br>    user-api.test.ts</pre><p>First, let’s create a logger:</p><pre>// src/utils/logger.ts<br>import fs from &#39;fs&#39;;<br>import path from &#39;path&#39;;<br><br>export enum LogLevel {<br>  DEBUG = 0,<br>  INFO = 1,<br>  WARN = 2,<br>  ERROR = 3,<br>  NONE = 4<br>}<br><br>export class Logger {<br>  private static logLevel: LogLevel = LogLevel.INFO;<br>  private static logToFile: boolean = false;<br>  private static logFilePath: string = path.join(process.cwd(), &#39;logs&#39;, &#39;api-tests.log&#39;);<br>  <br>  static configure(options: {<br>    logLevel?: LogLevel,<br>    logToFile?: boolean,<br>    logFilePath?: string<br>  }) {<br>    if (options.logLevel !== undefined) {<br>      this.logLevel = options.logLevel;<br>    }<br>    <br>    if (options.logToFile !== undefined) {<br>      this.logToFile = options.logToFile;<br>      <br>      // Ensure log directory exists<br>      if (this.logToFile) {<br>        const logDir = path.dirname(this.logFilePath);<br>        if (!fs.existsSync(logDir)) {<br>          fs.mkdirSync(logDir, { recursive: true });<br>        }<br>      }<br>    }<br>    <br>    if (options.logFilePath) {<br>      this.logFilePath = options.logFilePath;<br>    }<br>    <br>    this.info(`Logger configured: level=${LogLevel[this.logLevel]}, logToFile=${this.logToFile}`);<br>  }<br>  <br>  private static writeToFile(message: string) {<br>    if (!this.logToFile) return;<br>    <br>    const timestamp = new Date().toISOString();<br>    const logMessage = `[${timestamp}] ${message}\n`;<br>    <br>    fs.appendFileSync(this.logFilePath, logMessage);<br>  }<br>  <br>  static debug(message: string, data?: any) {<br>    if (this.logLevel &lt;= LogLevel.DEBUG) {<br>      const dataString = data ? `: ${JSON.stringify(data, null, 2)}` : &#39;&#39;;<br>      const fullMessage = `[DEBUG] ${message}${dataString}`;<br>      console.debug(fullMessage);<br>      this.writeToFile(fullMessage);<br>    }<br>  }<br>  <br>  static info(message: string, data?: any) {<br>    if (this.logLevel &lt;= LogLevel.INFO) {<br>      const dataString = data ? `: ${JSON.stringify(data, null, 2)}` : &#39;&#39;;<br>      const fullMessage = `[INFO] ${message}${dataString}`;<br>      console.info(fullMessage);<br>      this.writeToFile(fullMessage);<br>    }<br>  }<br>  <br>  static warn(message: string, data?: any) {<br>    if (this.logLevel &lt;= LogLevel.WARN) {<br>      const dataString = data ? `: ${JSON.stringify(data, null, 2)}` : &#39;&#39;;<br>      const fullMessage = `[WARN] ${message}${dataString}`;<br>      console.warn(fullMessage);<br>      this.writeToFile(fullMessage);<br>    }<br>  }<br>  <br>  static error(message: string, data?: any) {<br>    if (this.logLevel &lt;= LogLevel.ERROR) {<br>      const dataString = data ? `: ${JSON.stringify(data, null, 2)}` : &#39;&#39;;<br>      const fullMessage = `[ERROR] ${message}${dataString}`;<br>      console.error(fullMessage);<br>      this.writeToFile(fullMessage);<br>    }<br>  }<br><br>  static logRequest(method: string, url: string, headers: Record&lt;string, any&gt;, body?: any) {<br>    if (this.logLevel &lt;= LogLevel.INFO) {<br>      this.info(`API Request: ${method} ${url}`);<br>      this.debug(&#39;Request Headers&#39;, headers);<br>      <br>      if (body) {<br>        this.debug(&#39;Request Body&#39;, body);<br>      }<br>    }<br>  }<br><br>  static logResponse(status: number, headers: Record&lt;string, any&gt;, body: any, duration: number) {<br>    if (this.logLevel &lt;= LogLevel.INFO) {<br>      this.info(`API Response (${duration}ms): Status ${status}`);<br>      this.debug(&#39;Response Headers&#39;, headers);<br>      this.debug(&#39;Response Body&#39;, body);<br>    }<br>  }<br>  <br>  static logError(error: any) {<br>    this.error(&#39;Error occurred&#39;, {<br>      message: error.message,<br>      stack: error.stack,<br>      response: error.response ? {<br>        status: error.response.status,<br>        body: error.response.body<br>      } : &#39;No response&#39;<br>    });<br>  }<br>}</pre><p>Next, let’s create test data generators:</p><pre>// src/utils/test-data.ts<br>import { User } from &#39;../models/user.model&#39;;<br>import { Post } from &#39;../models/post.model&#39;;<br>import { Logger } from &#39;./logger&#39;;<br><br>export class TestData {<br>  static generateUser(overrides: Partial&lt;User&gt; = {}): User {<br>    Logger.debug(&#39;Generating test user data&#39;, overrides);<br>    <br>    return {<br>      id: Math.floor(Math.random() * 1000),<br>      name: &#39;Test User&#39;,<br>      username: &#39;testuser&#39;,<br>      email: &#39;test@example.com&#39;,<br>      address: {<br>        street: &#39;123 Main St&#39;,<br>        suite: &#39;Apt 1&#39;,<br>        city: &#39;Testville&#39;,<br>        zipcode: &#39;12345-6789&#39;,<br>        geo: {<br>          lat: &#39;0&#39;,<br>          lng: &#39;0&#39;<br>        }<br>      },<br>      phone: &#39;123-456-7890&#39;,<br>      website: &#39;test.com&#39;,<br>      company: {<br>        name: &#39;Test Co&#39;,<br>        catchPhrase: &#39;Testing is fun!&#39;,<br>        bs: &#39;test solutions&#39;<br>      },<br>      ...overrides<br>    };<br>  }<br><br>  static generatePost(overrides: Partial&lt;Post&gt; = {}): Post {<br>    Logger.debug(&#39;Generating test post data&#39;, overrides);<br>    <br>    return {<br>      userId: Math.floor(Math.random() * 10) + 1,<br>      id: Math.floor(Math.random() * 1000),<br>      title: &#39;Test Post Title&#39;,<br>      body: &#39;This is the body of a test post. It contains test content.&#39;,<br>      ...overrides<br>    };<br>  }<br>}</pre><p>Finally, a response validator:</p><pre>// src/utils/response-validator.ts<br>import { z } from &#39;zod&#39;;<br>import { Logger } from &#39;./logger&#39;;<br><br>export class ResponseValidator {<br>  static validate&lt;T&gt;(data: any, schema: z.ZodType&lt;T&gt;): T {<br>    try {<br>      Logger.debug(&#39;Validating response data against schema&#39;);<br>      return schema.parse(data);<br>    } catch (error) {<br>      Logger.error(&#39;Validation error:&#39;, error);<br>      throw error;<br>    }<br>  }<br>  <br>  static validateArray&lt;T&gt;(data: any, schema: z.ZodType&lt;T&gt;): T[] {<br>    if (!Array.isArray(data)) {<br>      const error = new Error(&#39;Expected an array but received: &#39; + typeof data);<br>      Logger.error(&#39;Validation error:&#39;, error);<br>      throw error;<br>    }<br>    <br>    try {<br>      Logger.debug(`Validating array of ${data.length} items`);<br>      return data.map((item, index) =&gt; {<br>        try {<br>          return schema.parse(item);<br>        } catch (error) {<br>          Logger.error(`Validation error at index ${index}:`, error);<br>          throw error;<br>        }<br>      });<br>    } catch (error) {<br>      Logger.error(&#39;Array validation error:&#39;, error);<br>      throw error;<br>    }<br>  }<br>}</pre><p>Now we can update our user API to use these utilities:</p><pre>// src/api/user-api.ts<br>import { apiContext } from &#39;./api-context&#39;;<br>import { User, UserSchema, UsersSchema } from &#39;../models/user.model&#39;;<br>import { Logger } from &#39;../utils/logger&#39;;<br>import { ResponseValidator } from &#39;../utils/response-validator&#39;;<br><br>export async function getUsers() {<br>  try {<br>    Logger.info(&#39;Fetching all users&#39;);<br>    const response = await apiContext.get(&#39;/users&#39;);<br>    <br>    // Validate response against our schema<br>    const validatedData = ResponseValidator.validateArray(response.body, UserSchema);<br>    Logger.info(`Retrieved ${validatedData.length} users`);<br>    <br>    return {<br>      ...response,<br>      body: validatedData<br>    };<br>  } catch (error) {<br>    Logger.error(&#39;Error fetching users&#39;, error);<br>    throw error;<br>  }<br>}<br><br>export async function getUserById(id: number) {<br>  try {<br>    Logger.info(`Fetching user with ID: ${id}`);<br>    const response = await apiContext.get(`/users/${id}`);<br>    <br>    // Validate response against our schema<br>    const validatedData = ResponseValidator.validate(response.body, UserSchema);<br>    Logger.info(`Retrieved user: ${validatedData.name}`);<br>    <br>    return {<br>      ...response,<br>      body: validatedData<br>    };<br>  } catch (error) {<br>    Logger.error(`Error fetching user with ID: ${id}`, error);<br>    throw error;<br>  }<br>}</pre><h3>Part 9: Environment Configuration</h3><p>Let’s add environment-specific configuration:</p><p>First, create a .env file:</p><pre># .env<br>API_ENV=dev</pre><p>Create an environment config file:</p><pre>// src/config/env-config.ts<br>import dotenv from &#39;dotenv&#39;;<br><br>dotenv.config();<br><br>type Environment = &#39;dev&#39; | &#39;staging&#39; | &#39;prod&#39;;<br><br>const env: Environment = (process.env.API_ENV as Environment) || &#39;dev&#39;;<br><br>const environments = {<br>  dev: {<br>    baseUrl: &#39;https://jsonplaceholder.typicode.com&#39;,<br>    timeoutMs: 30000,<br>  },<br>  staging: {<br>    baseUrl: &#39;https://staging-api.example.com&#39;,<br>    timeoutMs: 45000,<br>  },<br>  prod: {<br>    baseUrl: &#39;https://api.example.com&#39;,<br>    timeoutMs: 60000,<br>  }<br>};<br><br>export const EnvConfig = {<br>  env,<br>  ...environments[env],<br>  defaultHeaders: {<br>    &#39;Content-Type&#39;: &#39;application/json&#39;<br>  }<br>};</pre><p>Update our API config to use this environment config:</p><pre>// src/config/api-config.ts<br>import { EnvConfig } from &#39;./env-config&#39;;<br><br>export const ApiConfig = {<br>  baseUrl: EnvConfig.baseUrl,<br>  timeoutMs: EnvConfig.timeoutMs,<br>  defaultHeaders: EnvConfig.defaultHeaders<br>};</pre><p>Now we can easily switch environments by changing the API_ENV variable.</p><h3>Part 10: Demonstrating Scalability — Adding a New Endpoint</h3><p>Let’s add a new endpoint for posts to demonstrate scalability:</p><p>First, create a model for posts:</p><pre>// src/models/post.model.ts<br>import { z } from &#39;zod&#39;;<br><br>export const PostSchema = z.object({<br>  userId: z.number(),<br>  id: z.number(),<br>  title: z.string(),<br>  body: z.string()<br>});<br><br>export type Post = z.infer&lt;typeof PostSchema&gt;;<br><br>export const PostsSchema = z.array(PostSchema);</pre><p>Create an API handler for posts:</p><pre>// src/api/post-api.ts<br>import { apiContext } from &#39;./api-context&#39;;<br>import { Post, PostSchema, PostsSchema } from &#39;../models/post.model&#39;;<br>import { Logger } from &#39;../utils/logger&#39;;<br>import { ResponseValidator } from &#39;../utils/response-validator&#39;;<br><br>export async function getPosts() {<br>  try {<br>    Logger.info(&#39;Fetching all posts&#39;);<br>    const response = await apiContext.get(&#39;/posts&#39;);<br>    <br>    // Validate response against our schema<br>    const validatedData = ResponseValidator.validateArray(response.body, PostSchema);<br>    Logger.info(`Retrieved ${validatedData.length} posts`);<br>    <br>    return {<br>      ...response,<br>      body: validatedData<br>    };<br>  } catch (error) {<br>    Logger.error(&#39;Error fetching posts&#39;, error);<br>    throw error;<br>  }<br>}<br><br>export async function getPostById(id: number) {<br>  try {<br>    Logger.info(`Fetching post with ID: ${id}`);<br>    const response = await apiContext.get(`/posts/${id}`);<br>    <br>    // Validate response against our schema<br>    const validatedData = ResponseValidator.validate(response.body, PostSchema);<br>    Logger.info(`Retrieved post: ${validatedData.title}`);<br>    <br>    return {<br>      ...response,<br>      body: validatedData<br>    };<br>  } catch (error) {<br>    Logger.error(`Error fetching post with ID: ${id}`, error);<br>    throw error;<br>  }<br>}<br><br>export async function getPostsByUser(userId: number) {<br>  try {<br>    Logger.info(`Fetching posts for user ID: ${userId}`);<br>    const response = await apiContext.get(`/users/${userId}/posts`);<br>    <br>    // Validate response against our schema<br>    const validatedData = ResponseValidator.validateArray(response.body, PostSchema);<br>    Logger.info(`Retrieved ${validatedData.length} posts for user ${userId}`);<br>    <br>    return {<br>      ...response,<br>      body: validatedData<br>    };<br>  } catch (error) {<br>    Logger.error(`Error fetching posts for user ID: ${userId}`, error);<br>    throw error;<br>  }<br>}</pre><p>Finally, create tests for the posts endpoint:</p><pre>// src/__tests__/post-api.test.ts<br>import { expect } from &#39;chai&#39;;<br>import { getPosts, getPostById, getPostsByUser, createPost, updatePost, deletePost } from &#39;../api/post-api&#39;;<br>import { Post } from &#39;../models/post.model&#39;;<br>import { TestData } from &#39;../utils/test-data&#39;;<br><br>describe(&#39;Post API&#39;, () =&gt; {<br>  it(&#39;should return a list of posts&#39;, async () =&gt; {<br>    const response = await getPosts();<br>    const posts: Post[] = response.body;<br>    <br>    expect(response.status).to.equal(200);<br>    expect(posts).to.be.an(&#39;array&#39;);<br>    expect(posts.length).to.be.greaterThan(0);<br>    expect(posts[0]).to.have.property(&#39;title&#39;);<br>    expect(posts[0]).to.have.property(&#39;body&#39;);<br>  });<br><br>  it(&#39;should return a single post by ID&#39;, async () =&gt; {<br>    const response = await getPostById(1);<br>    const post: Post = response.body;<br>    <br>    expect(response.status).to.equal(200);<br>    expect(post.id).to.equal(1);<br>    expect(post).to.have.property(&#39;title&#39;);<br>    expect(post).to.have.property(&#39;body&#39;);<br>  });<br><br>  it(&#39;should return posts by user ID&#39;, async () =&gt; {<br>    const userId = 1;<br>    const response = await getPostsByUser(userId);<br>    const posts: Post[] = response.body;<br>    <br>    expect(response.status).to.equal(200);<br>    expect(posts).to.be.an(&#39;array&#39;);<br>    expect(posts.length).to.be.greaterThan(0);<br>    expect(posts.every(post =&gt; post.userId === userId)).to.be.true;<br>  });<br>});</pre><p>Notice how we didn’t have to modify any of our user tests or helpers to add this new functionality. This is the power of a well-structured framework!</p><h3>Conclusion</h3><p>We’ve built a robust API testing framework from scratch using TypeScript and Supertest. Starting with a single simple test, we progressively refactored it into a professional, scalable framework.</p><p>Here’s what we’ve accomplished:</p><ul><li>Strong type safety with TypeScript models</li><li>Runtime validation with Zod</li><li>Centralized configuration for different environments</li><li>Reusable utilities for common operations</li><li>Clean separation of concerns</li><li>Easily extensible structure for new endpoints</li></ul><p>This approach gives you a deep understanding of how each piece fits together, unlike simply copying an existing framework. You can now confidently add new tests, endpoints, and functionality as your API grows.</p><p><a href="https://github.com/hiroksarker/api-testing-framework.git">Git url</a> : <a href="https://github.com/hiroksarker/api-testing-framework.git">https://github.com/hiroksarker/api-testing-framework.git</a></p><p>Contributed and Reviewed by:<a href="https://medium.com/@humayunahmedashik">https://medium.com/@humayunahmedashik</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6dbe23e7dacd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Blockchain Testing Methodology]]></title>
            <link>https://hirok-sarker.medium.com/what-is-blockchain-79bf19d17a91?source=rss-a3df8e53780e------2</link>
            <guid isPermaLink="false">https://medium.com/p/79bf19d17a91</guid>
            <category><![CDATA[blockchain-technology]]></category>
            <category><![CDATA[methodology]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Hirok Sarker]]></dc:creator>
            <pubDate>Fri, 04 Jun 2021 05:44:23 GMT</pubDate>
            <atom:updated>2021-06-04T05:49:29.422Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is Blockchain?</h3><p>The world these days is about virtual, digital, and cryptocurrencies in different shapes and sizes (read as rates and valuation respectively) that heavily rely on technology. Blockchain is a distributed ledger, which is validated among different business peers. This ledger further acts like an immutable audit log.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*PwFo86EeHSnGejSaEJRWjg.jpeg" /></figure><p><strong>Blockchain Feature</strong></p><p><strong>BLOCKCHAIN LEDGER</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/51/0*PKo03yrLJk82SJ5r.png" /></figure><blockquote><em>Decentralized</em></blockquote><blockquote><em>Immutability</em></blockquote><blockquote><em>Consensus Mechanism</em></blockquote><blockquote><em>Smart Contracts</em></blockquote><blockquote><em>Fault Tolerant</em></blockquote><p><strong>VALUE</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/57/0*DXgS-u0FWFgKY6oC.png" /></figure><blockquote><em>Trust</em></blockquote><blockquote><em>Auditability</em></blockquote><blockquote><em>Security</em></blockquote><blockquote><em>Automation</em></blockquote><blockquote><em>Availability</em></blockquote><p><strong>Different Types of Blockchain</strong></p><p><strong>Public</strong></p><p>Public, Permission less Blockchain</p><p>Allow access to any user at any time, ledger management is facilitated by the distributed network (e.g. Bitcoin, Ethereum)</p><p><strong>Consortium</strong></p><p>Federated, Permissioned Blockchain(Single or Multi-Industry)</p><p>Allow access to users based on the rules defined by the group of entities (consortium) participation in the network, ledger management is facilitated by the consortium (e.g., Ripple, R3, Corda</p><p><em>Permissioned by many</em></p><p><strong>Private</strong></p><p>Private, Permissioned Blockchains</p><p>Allow access to users based on the permission set by the private network, ledger management is facilitated by single company for private use (e.g., Chain, Supplychain, Bankchain)</p><p><em>Permissioned by one</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*zdsu5D2BuvmZ-wB6xPa0GQ.png" /></figure><p><strong>What does it mean for testing?</strong></p><p>Challenges in Testing the Blockchain</p><ul><li><strong><em>Understating the technology</em></strong></li></ul><p>Blockchain is a relatively new technology</p><ul><li><strong><em>Lack of Blockchain Testing Tools</em></strong></li></ul><p>Picking up the right tool as per the application is a crucial decision</p><ul><li><strong><em>Lack of Best Practices</em></strong></li></ul><p>New Technology, lack of experience to test blockchain application</p><ul><li><strong><em>Defining the Test Strategy</em></strong></li></ul><p>Requires a deep understanding of the application</p><ul><li><strong><em>Addition of Blocks</em></strong></li></ul><p>Validate all the blocks that get added to the chain post authentication of every transaction</p><ul><li><strong><em>Block and Chain size</em></strong></li></ul><p>A block contains real-time ledger record with encryption and timestamp</p><p>The chain size can be many blocks as the chain lengthens</p><ul><li><strong><em>Transmission of Crypto-Graphical Data</em></strong></li><li><strong><em>Integration Testing</em></strong></li></ul><p>The key responsibility is to ensure that the response from all interfaces is consistent and there are no disconnects</p><ul><li><strong><em>Security Testing</em></strong></li></ul><p>Human-related risks</p><p>Risks with private and public key</p><p>Vendors Risks and Untested code</p><p>Lack of Standards and Regulation</p><ul><li><strong><em>Performance and Load Testing</em></strong></li></ul><p>Focus on:</p><p>Network latency</p><p>Performance bottlenecks</p><p>The sequence of transaction at every node</p><p>Transaction processing speed</p><p>Client/User and system interface</p><p>The responses required from the smart contracts</p><p><strong>Why existing Testing solutions are inadequate?</strong></p><p><strong>To the best of our knowledge</strong> there is no defined process or approach used for testing Blockchain solutions that covers all the dimensions or complexities of Blockchain implementations.</p><p><strong>Adhoc testing methodologies</strong> an processes are used that may leave Blockchain systems immune to defects and production failures. Our proprietary methodology covers all the aspect of testing requirement for a production grade implementation.</p><p>Testing approach should not be platform specific. Client’s solutions which are built on existing blockchain platforms should not focus extensively on technical features which are applicable for the specific platform. For example, the way a DLT platform stores users’ credentials is not something that need to be tested. It’s the platform’s responsibility to provide these kind of warranties for their software. However, when using 100% open source platforms we do need to do this level of testing.</p><p><strong>Testing Decentralized Solutions</strong></p><p><strong>Traditional V-Model Test</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*QGUWxIcUuqCL3Q3Ot8U91g.png" /><figcaption><em>v-model test</em></figcaption></figure><p><strong>Adopted for Blockchain (Verification and Testing)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*olUtjvIJI4f9cuBma0fx2A.png" /><figcaption><em>Proposed Blockchain (Verification and Testing)</em></figcaption></figure><p><strong>Blockchain Ecosystem</strong></p><p>Elements that should be considered while planning the QA approach:</p><p><strong>1. Standard Testing &amp; Validation</strong></p><ul><li><strong><em>Functional Testing</em></strong></li></ul><p>Testing of individual components and system including User Acceptance Testing</p><ul><li><strong><em>Integration Testing</em></strong></li></ul><p>Interfaces between components and different parts of the system which can be on different environment</p><p><strong>2. Non-Function Testing</strong></p><ul><li><strong><em>Security Testing</em></strong></li></ul><p>Testing for confidentiality, integrity, authentication, access, and authorization are critical components of security</p><ul><li><strong><em>Performance Testing</em></strong></li></ul><p>The performance and latency vary with the size of network and size of transactions</p><p><strong>3. Testing specific to Blockchain</strong></p><ul><li><strong><em>Peer/Node Testing</em></strong></li></ul><p>The strength of the blockchain lies in having the shared ledger be exactly the same at each and every node</p><ul><li><strong><em>Smart Contract Testing</em></strong></li></ul><p>Software modules on the blockchain that automatically execute transactions based on pre-defined conditions.</p><p><strong>Blockchain Testing Considered</strong> (Specific in the Blockchain solution testing to be considered.)</p><p><strong>Blockchain Transactions</strong></p><ul><li><strong><em>Transaction processing</em></strong></li></ul><p>Validation of transaction lifecycle through Apps / Vaults / Wallets</p><ul><li><strong><em>Transaction State / Event</em></strong></li></ul><p>Proof of distribution</p><p>Basic data model for Blockchain</p><p>Validation of event notification</p><ul><li><strong><em>Vault / Wallet</em></strong></li></ul><p>Validation of Transactions message verification (signing)</p><p>Common trusted database</p><p>Storage algorithm</p><p>Extensive testing of wallets or hashing algorithms in enterprise blockchain would be more required on 100% open source / permission less solutions</p><p><strong>Blockchain Governance</strong></p><ul><li><strong><em>History &amp; Audit</em></strong></li></ul><p>Validation of secure registry and audit of transaction</p><p>Immutable record</p><p>Secure Identifications of assets</p><ul><li><strong><em>Consensus Mechanism</em></strong></li></ul><p>Consolidated consistent dataset</p><p>Various consensus models (PoW, PoS, Byzantine FT)</p><p>Transaction timestamping</p><ul><li><strong><em>Smart Contract</em></strong></li></ul><p>Validation of business rules through Smart Contracts:</p><p>Self-enforcing contracts</p><p>Digitized analog contracts</p><p>Real-time auditing of transactions</p><p><strong>Blockchain Platform</strong></p><ul><li><strong><em>Interaction with APIS</em></strong></li></ul><p>Validation of interface with API’s for access control payments, track and trace and balances.</p><ul><li><strong><em>Key &amp; Identify Services</em></strong></li></ul><p>Consortium or private blockchains</p><p>Public blockchains</p><p>Validation of tokenization of assets</p><ul><li><strong><em>Blockchain Applications</em></strong></li></ul><p>Web Application</p><p>Native Application</p><p>Wallet / Vault Applications</p><p>Blockchain testing part of a knowledge sharing platform to leverage up to date information about blockchain and QA. Leverage testing methods and techniques that has been generally accepted and proven in real project. Collaboration between business, developers and QA teams to achieve best possible result.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79bf19d17a91" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Performance and Functional Testing using TAURUS (Blazemeter)]]></title>
            <link>https://hirok-sarker.medium.com/performance-and-functional-testing-using-taurus-blazemeter-bb9451a028ee?source=rss-a3df8e53780e------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb9451a028ee</guid>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Hirok Sarker]]></dc:creator>
            <pubDate>Fri, 01 Nov 2019 17:25:30 GMT</pubDate>
            <atom:updated>2019-11-01T17:25:30.652Z</atom:updated>
            <content:encoded><![CDATA[<p>I am always wondering to know something new in Testing (Automation &amp; Performance). Last few months fully concentrating on Automation, Performance and Functional Testing. Though today discusses performance and functional testing using TAURUS (Automation-friendly framework for Continuous Testing) open-source project created by BlazeMeter and great community members who are always contributing to help our technology community. Those who are using JMeter for performance and functional testing, you will happy to hear that TAURUS helps you to see the real-time performance and function testing and BlazeMeter Report.</p><p><strong>Why TAURUS: </strong><br>Hides the complexity of performance and functional tests with an automation-friendly convenience wrapper. Taurus relies on JMeter, Gatling, Locust.io, Grinder and Selenium WebDriver as its underlying tools. Free and open source under Apache 2.0 License.</p><blockquote>Resource Documentation: <br> Url: <a href="http://gettaurus.org/docs/Index/">http://gettaurus.org/docs/Index/</a><br> Github Url: <a href="https://github.com/Blazemeter/taurus">https://github.com/Blazemeter/taurus</a></blockquote><p>If you are using multiple testing executor. Don’t worry also TAURUS has great features.<br><strong>Supporting Testing Executor:</strong><br>(<em>JMeter, Selenium, JUnit, TestNG, Apiritif, PyTest, RSpec, Mocha, WebdriverIO, NUnit, Robot, Gatling, Grinder, Locust, PBench, Siege, ApacheBenchmark, Tsung, Molotov, Postman/Newman</em>) executor and also Existing Results Loader.</p><blockquote>Install Process: Url: <a href="http://gettaurus.org/install/Installation/">http://gettaurus.org/install/Installation/</a></blockquote><p>Full details information on how to install TAURUS and also all kinds of operating system support.</p><blockquote>jMeter Executor Download and Example:<br> Download Taurus Installer Software and Install. Windows — <a href="https://gettaurus.org/builds/TaurusInstaller_1.13.9_x64.exe">https://gettaurus.org/builds/TaurusInstaller_1.13.9_x64.exe</a></blockquote><blockquote>Windows User:-&gt; Run Command Prompt — cmd<br> -&gt; bzt jMeter .jmx file full location like (C:\Users\jmx\testing.jmx) Example: bzt C:\Users\jmx\testing.jmx<br> -&gt; run</blockquote><blockquote>Sample Execution Code:<br> INFO: Taurus CLI Tool v1.13.9<br> INFO: Starting with configs: [‘C:\\Users\\jmx\testing.jmx’]<br> INFO: Configuring…<br> INFO: Artifacts dir: C:\Users\2019–11–01_21–07–26.754978<br> INFO: Preparing…<br> INFO: Starting…</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-n9mEnlvdJha4aismz5UnQ.jpeg" /></figure><blockquote>Also have YMAL support: <br>execution:<br>- scenario: simple</blockquote><blockquote>scenarios:<br> simple:<br> script: tests/jmx/testing.jmx</blockquote><p>save file as test.yml<br>Windows User (yml run command):</p><blockquote>-&gt; Run Command Prompt<br> -&gt; bzt yml file full location like (C:\Users\yml\test.yml) Example: bzt C:\Users\yml\test.yml<br> -&gt; run</blockquote><p>jMeter Taurus Configuration Details: <a href="http://gettaurus.org/docs/JMeter/">http://gettaurus.org/docs/JMeter/</a> and see as your requirement.<br>Automation-friendly framework for Continuous Testing by <a href="http://gettaurus.org/">http://gettaurus.org</a><br>Thanks</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb9451a028ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to fixed Postman API Test Collection using Nodejs (newman)and Unicode Problem Windows 10]]></title>
            <link>https://hirok-sarker.medium.com/how-to-fixed-postman-api-test-collection-using-nodejs-newman-and-unicode-problem-windows-10-483f875467b9?source=rss-a3df8e53780e------2</link>
            <guid isPermaLink="false">https://medium.com/p/483f875467b9</guid>
            <category><![CDATA[postman]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <dc:creator><![CDATA[Hirok Sarker]]></dc:creator>
            <pubDate>Tue, 22 Oct 2019 09:52:31 GMT</pubDate>
            <atom:updated>2019-10-22T10:00:11.140Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to fix Postman API Test Collection using Nodejs (newman)and Unicode Problem Windows 10</h3><p>Our main goal of continuous integration is to identify the problems that may occur during the development process earlier and more easily.</p><p>Passionate about automation and optimizing the best processes. Continuous Integration (CI) is a software development practice that is based on a frequent integration of the code into a shared repository.</p><p>Most commonly used Jenkins because Jenkins is an open-source automation server. Its main objectives are to detect changes in subversion or git and to perform tasks repeatedly (i.e., build, test, deploy, package, integrate). In general, Jenkins allows one to create a complete CI cycle.</p><p>Continuous Integration Systems has many benefits but sometimes face setup related issues. To fixed two-issue windows to console reports and Unicode related issues.</p><p><strong>How to run <em>newman</em> command in Jenkins-</strong></p><p>Pre-requirement — Install Nodejs — <a href="https://nodejs.org/en/"><em>https://nodejs.org/en/</em></a></p><p>Choose new FreeStyle Project-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cAFbHQ0-p5QTMwHG9QHI8g.jpeg" /></figure><p>Then choose Build &gt; Execute Windows batch command</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J-6Twaycap-E0MiQ9Ss_pQ.jpeg" /></figure><p>The console output result should look like this: (Windows)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*zItXmCMfQscKBFiN9W6lWw.jpeg" /></figure><p>Ok. Now everything ready but newman issue. Now we need to fix that newman issue.</p><p>First Need to install — <em>Nodejs Plugin &gt; Manage Plugins &gt; Available &gt; Search — Nodejs &gt; Check box &gt; Install and Restart</em></p><p>Now let’s go to Jenkins &gt; <em>Manage Jenkins &gt; Global Tools Configuration</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XIzJvlGk5HACA7pvUmlrMA.jpeg" /></figure><p>Apply then Save. :)</p><p>Now Edit Project —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YWkqvp5KBlCoo4pA5hyJZg.jpeg" /></figure><p>Check box click — <em>Provide Node &amp; npm bin / folder to PATH. </em>Apply &amp; Save</p><p>Again Build Now —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lAgSyc5sIKQWNLAxf4nYUg.jpeg" /></figure><p>Congratulations! but one more issue again. Unicode related issue :(.</p><p>UTF-8 encoding issue resolution method in Jenkins — (One)</p><p>Go to Install Project directory — <em>C:\Program Files (x86)\Jenkins</em></p><p>Open &gt; <em>jenkins.xml</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eAsi0AEYA09vLWEcNfHJqw.jpeg" /></figure><blockquote>-Dfile.encoding=UTF8</blockquote><p>Save then Restart — <em>Jenkins Service</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*xtSIFGUmM_xwsrtwPleoxg.jpeg" /></figure><p>Again Build Now —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*qDzSwGFxB_afD22m1f_tBw.jpeg" /></figure><p>Congratulations and Successfully Fixed Unicode Issue.</p><p>Another different way to fix Unicode issue -</p><p>To resolve the encoding issue we have to add the environment variable in system as shown below first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*EhzpGmPTQm4JawMAs_tn5w.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*QhIbJu1Z_QM5Rp2qJNZ_Pg.jpeg" /></figure><p>Save then Restart — <em>Jenkins Service</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*7pkFv25EzHpmWPJBGXplDA.jpeg" /></figure><p>These environment variables were added in Jenkins as well which has resolved the encoding issue.</p><p><em>Jenkins -&gt; Manage Jenkins -&gt; Configure System -&gt;Global properties.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=483f875467b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>