<?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 Wavda Aniva on Medium]]></title>
        <description><![CDATA[Stories by Wavda Aniva on Medium]]></description>
        <link>https://medium.com/@anivaz?source=rss-beb8620860f2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*YtzuCNyrChxuOpWNFciang.png</url>
            <title>Stories by Wavda Aniva on Medium</title>
            <link>https://medium.com/@anivaz?source=rss-beb8620860f2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 15:15:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anivaz/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[Building a Lightweight Screen Recorder for Selenium Tests: No Dependencies, No Headaches]]></title>
            <link>https://anivaz.medium.com/building-a-lightweight-screen-recorder-for-selenium-tests-no-dependencies-no-headaches-116cf1884ccf?source=rss-beb8620860f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/116cf1884ccf</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[selenium]]></category>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[cicd]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Wavda Aniva]]></dc:creator>
            <pubDate>Mon, 18 Aug 2025 13:02:21 GMT</pubDate>
            <atom:updated>2025-08-18T13:58:24.463Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How we solved the test recording problem for headless browsers in CI/CD environments with a custom solution.</em></p><h3><strong>The Problem That Every Test Automation Engineer Faces</strong></h3><p>Picture this: Your Selenium tests are running perfectly on your local machine, but when they fail in your CI/CD pipeline (TeamCity, Jenkins, GitHub Actions), you’re left staring at cryptic error messages with zero visual context. You know something went wrong, but <em>what exactly happened</em> remains a mystery.</p><p>Most teams reach for popular screen recording libraries or external tools. But here’s where the pain begins:</p><h4><strong>The Dependency Hell</strong></h4><ul><li><strong>Heavy dependencies</strong>: Most screen recording libraries require AWT, Swing, or native libraries</li><li><strong>Platform-specific requirements</strong>: Different solutions for Windows, Linux, and macOS</li><li><strong>Version conflicts</strong>: Incompatibilities with your existing Selenium/TestNG stack</li><li><strong>Setup complexity</strong>: Additional configuration files, native binaries, system-level permissions</li></ul><h4><strong>The Headless Nightmare</strong></h4><p>The real killer? <strong>None of these solutions works reliably in headless environments.</strong></p><p>When your tests run on Linux agents with no display server (TeamCity, Jenkins slaves, Docker containers), traditional screen recorders fail silently or throw cryptic exceptions. Your CI logs become useless, and debugging becomes guesswork.</p><h3><strong>The Lightweight Solution: Screenshot-Based Recording</strong></h3><p>After battling these issues across multiple projects, we built a custom screen recorder that solves all these problems with a surprisingly simple approach:</p><p><strong>Instead of trying to record the screen directly, capture periodic screenshots and compile them into a video.</strong></p><h4><strong>Why This Works Brilliantly</strong></h4><p>1. <strong>Zero dependencies</strong>: Uses only Selenium’s built-in screenshot capability</p><p>2. <strong>Headless-friendly</strong>: Screenshots work perfectly in headless browsers</p><p>3. <strong>Cross-platform</strong>: Identical behavior on Windows, Linux, macOS</p><p>4. <strong>Lightweight</strong>: Minimal memory footprint, no native libraries</p><p>5. <strong>Reliable</strong>: If Selenium can take screenshots, recording works</p><h4><strong>Architecture Overview</strong></h4><p>This solution consists of three main components:</p><pre>public class ScreenRecorder {<br>    // 1. Screenshot capture with configurable frame rate<br>    // 2. Temporary frame storage<br>    // 3. FFmpeg video compilation<br>}</pre><h4><strong>Core Features</strong></h4><ul><li><strong>Thread-safe singleton pattern</strong>: Safe for parallel test execution</li><li><strong>Configurable frame rates</strong>: Balance between quality and performance</li><li><strong>Automatic cleanup</strong>: Temporary files are managed automatically</li><li><strong>Graceful fallback</strong>: Works with or without FFmpeg installed</li><li><strong>Smart naming</strong>: Videos are automatically named based on test methods</li></ul><h3><strong>Implementation</strong></h3><pre>import java.io.File;<br>import java.io.IOException;<br>import java.nio.file.Files;<br>import java.nio.file.Path;<br>import java.nio.file.Paths;<br>import java.time.LocalDateTime;<br>import java.time.format.DateTimeFormatter;<br>import java.util.concurrent.Executors;<br>import java.util.concurrent.ScheduledExecutorService;<br>import java.util.concurrent.TimeUnit;<br>import java.util.concurrent.atomic.AtomicInteger;<br><br>import org.apache.logging.log4j.LogManager;<br>import org.apache.logging.log4j.Logger;<br>import org.openqa.selenium.OutputType;<br>import org.openqa.selenium.TakesScreenshot;<br>import org.openqa.selenium.WebDriver;<br>import org.openqa.selenium.WebDriverException;<br><br>/**<br> * Thread-safe utility class for recording video from screenshots in headless<br> * mode. This approach takes periodic screenshots and compiles them into a video<br> * using FFmpeg.<br> *<br> */<br>public class ScreenRecorder {<br><br>    private static final Logger logger = LogManager.getLogger(ScreenRecorder.class);<br><br>    // Constants<br>    private static final int DEFAULT_FRAME_RATE = 10;<br>    private static final int SHUTDOWN_TIMEOUT_SECONDS = 5;<br>    private static final String FRAME_NAME_FORMAT = &quot;frame_%06d.png&quot;;<br>    private static final String TIMESTAMP_FORMAT = &quot;yyyyMMdd_HHmmss&quot;;<br>    private static final String WATERMARK_TEXT = &quot;automation test recording on-going&quot;;<br><br>    // Video encoding settings<br>    private static final String VIDEO_CODEC = &quot;libx264&quot;;<br>    private static final String ENCODING_PRESET = &quot;ultrafast&quot;;<br>    private static final String CRF_VALUE = &quot;23&quot;;<br><br>    // Singleton instance - using initialization-on-demand holder pattern<br>    private static class InstanceHolder {<br>        private static final ScreenRecorder INSTANCE = new ScreenRecorder();<br>    }<br><br>    // Recording state<br>    private volatile boolean isRecording = false;<br><br>    // Recording configuration<br>    private int frameRate = DEFAULT_FRAME_RATE;<br>    private String recordingId;<br>    private String cachedOutputPath;<br><br>    // Resources<br>    private ScheduledExecutorService executor;<br>    private Path tempDir;<br>    private AtomicInteger frameCounter;<br>    private WebDriver currentDriver;<br><br>    /**<br>     * Private constructor to enforce singleton pattern.<br>     */<br>    private ScreenRecorder() {<br>        // Private constructor for singleton<br>    }<br><br>    /**<br>     * Returns the singleton instance of ScreenshotRecorder. This method is<br>     * thread-safe using initialization-on-demand holder pattern.<br>     *<br>     * @return the singleton instance<br>     */<br>    public static ScreenRecorder getInstance() {<br>        return InstanceHolder.INSTANCE;<br>    }<br><br>    /**<br>     * Starts recording with automatic screenshot capture using specified frame<br>     * rate.<br>     *<br>     * @param driver the WebDriver instance to capture screenshots from<br>     * @param outputPath the base name for the output video file<br>     * @param frameRate the number of frames per second (must be positive)<br>     * @throws IllegalArgumentException if parameters are invalid<br>     */<br>    public void startRecording(WebDriver driver, String outputPath, int frameRate) {<br>        validateDriver(driver);<br>        validateOutputPath(outputPath);<br>        validateFrameRate(frameRate);<br><br>        synchronized (this) {<br>            if (isRecording) {<br>                logger.warn(&quot;Recording already in progress, stopping previous recording&quot;);<br>                stopRecording();<br>            }<br><br>            initializeRecordingSession(driver, outputPath, frameRate);<br>        }<br><br>        try {<br>            setupRecordingResources();<br>            startAutomaticCapture();<br><br>            logger.debug(&quot;Automatic video recording started - Output: {}, FPS: {}&quot;,<br>                    cachedOutputPath, frameRate);<br><br>        } catch (IOException e) {<br>            logger.error(&quot;Failed to start recording: {}&quot;, e.getMessage(), e);<br>            cleanup();<br>            throw new RuntimeException(&quot;Failed to start recording&quot;, e);<br>        }<br>    }<br><br>    /**<br>     * Stops the current recording session and creates the video file. This<br>     * method is thread-safe and can be called multiple times safely.<br>     */<br>    public void stopRecording() {<br>        synchronized (this) {<br>            if (!isRecording) {<br>                logger.warn(&quot;No recording in progress&quot;);<br>                return;<br>            }<br><br>            isRecording = false;<br>        }<br><br>        try {<br>            shutdownExecutor();<br><br>            int frameCount = frameCounter.get();<br>            logger.debug(&quot;Stopping recording with {} frames, output path: {}&quot;, frameCount, cachedOutputPath);<br><br>            if (frameCount &gt; 0) {<br>                createVideo();<br>            } else {<br>                logger.warn(&quot;No frames captured, skipping video creation&quot;);<br>            }<br><br>        } catch (Exception e) {<br>            logger.error(&quot;Error during recording stop: {}&quot;, e.getMessage(), e);<br>        } finally {<br>            cleanup();<br>        }<br>    }<br><br>    // ===== Validation Methods =====<br>    private void validateDriver(WebDriver driver) {<br>        if (driver == null) {<br>            throw new IllegalArgumentException(&quot;WebDriver cannot be null&quot;);<br>        }<br>    }<br><br>    private void validateOutputPath(String outputPath) {<br>        if (outputPath == null || outputPath.trim().isEmpty()) {<br>            throw new IllegalArgumentException(&quot;Output path cannot be null or empty&quot;);<br>        }<br>    }<br><br>    private void validateFrameRate(int frameRate) {<br>        if (frameRate &lt;= 0) {<br>            throw new IllegalArgumentException(&quot;Frame rate must be positive, got: &quot; + frameRate);<br>        }<br>    }<br><br>    // ===== Initialization Methods =====<br>    private void initializeRecordingSession(WebDriver driver, String outputPath, int frameRate) {<br>        this.currentDriver = driver;<br>        this.frameRate = frameRate;<br>        this.frameCounter = new AtomicInteger(0);<br>        this.isRecording = true;<br><br>        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern(TIMESTAMP_FORMAT));<br>        this.recordingId = System.currentTimeMillis() + &quot;_&quot; + timestamp;<br><br>        // Use provided outputPath, or generate default if not provided<br>        if (outputPath != null &amp;&amp; !outputPath.trim().isEmpty()) {<br>            // Ensure the output path has .mp4 extension<br>            this.cachedOutputPath = outputPath.endsWith(&quot;.mp4&quot;) ? outputPath : outputPath + &quot;.mp4&quot;;<br>            // Ensure it starts with ./ for relative paths<br>            if (!this.cachedOutputPath.startsWith(&quot;./&quot;) &amp;&amp; !this.cachedOutputPath.startsWith(&quot;/&quot;)) {<br>                this.cachedOutputPath = &quot;./&quot; + this.cachedOutputPath;<br>            }<br>        } else {<br>            // Fallback to default naming pattern<br>            this.cachedOutputPath = &quot;./target/video/screen-recording-&quot; + recordingId + &quot;.mp4&quot;;<br>        }<br>    }<br><br>    private void setupRecordingResources() throws IOException {<br>        tempDir = Files.createTempDirectory(&quot;selenium_frames_&quot; + System.currentTimeMillis());<br>        logger.debug(&quot;Created temp directory: {}&quot;, tempDir);<br>    }<br><br>    private void startAutomaticCapture() {<br>        captureScreenshot(); // Take initial screenshot<br><br>        executor = Executors.newSingleThreadScheduledExecutor(r -&gt; {<br>            Thread t = new Thread(r, &quot;ScreenshotRecorder-&quot; + recordingId);<br>            t.setDaemon(true);<br>            return t;<br>        });<br><br>        long intervalMs = 1000 / frameRate;<br>        executor.scheduleAtFixedRate(() -&gt; {<br>            if (isRecording &amp;&amp; currentDriver != null) {<br>                captureScreenshot();<br>            }<br>        }, intervalMs, intervalMs, TimeUnit.MILLISECONDS);<br>    }<br><br>    private void shutdownExecutor() {<br>        if (executor != null &amp;&amp; !executor.isShutdown()) {<br>            executor.shutdown();<br>            try {<br>                if (!executor.awaitTermination(SHUTDOWN_TIMEOUT_SECONDS, TimeUnit.SECONDS)) {<br>                    logger.warn(&quot;Executor did not terminate gracefully, forcing shutdown&quot;);<br>                    executor.shutdownNow();<br>                }<br>            } catch (InterruptedException e) {<br>                logger.warn(&quot;Interrupted while waiting for executor shutdown&quot;);<br>                executor.shutdownNow();<br>                Thread.currentThread().interrupt();<br>            }<br>        }<br>    }<br><br>    private void cleanup() {<br>        cleanupTempFiles();<br>        currentDriver = null;<br>        executor = null;<br>        tempDir = null;<br>        frameCounter = null;<br>    }<br><br>    // ===== Screenshot Capture Methods =====<br>    private void captureScreenshot() {<br>        try {<br>            if (currentDriver == null) {<br>                logger.warn(&quot;No driver available for screenshot&quot;);<br>                return;<br>            }<br><br>            TakesScreenshot ts = (TakesScreenshot) currentDriver;<br>            File screenshot = ts.getScreenshotAs(OutputType.FILE);<br><br>            // Save frame<br>            int frameNum = frameCounter.incrementAndGet();<br>            String frameName = String.format(FRAME_NAME_FORMAT, frameNum);<br>            Path framePath = tempDir.resolve(frameName);<br>            <br>            // Copy the screenshot file directly instead of reading as BufferedImage<br>            Files.copy(screenshot.toPath(), framePath);<br><br>            logger.debug(&quot;Captured screenshot frame #{}&quot;, frameNum);<br><br>        } catch (IOException | WebDriverException e) {<br>            logger.error(&quot;Failed to capture screenshot: {}&quot;, e.getMessage(), e);<br>        }<br>    }<br><br>    // ===== Video Creation Methods =====<br>    private void createVideo() {<br>        try {<br>            logger.debug(&quot;Creating video from {} frames to: {}&quot;, frameCounter.get(), cachedOutputPath);<br><br>            ensureOutputDirectoryExists();<br><br>            if (isFFmpegAvailable()) {<br>                logger.debug(&quot;FFmpeg is available, creating video with FFmpeg&quot;);<br>                createVideoWithFFmpeg();<br>            } else {<br>                logger.warn(&quot;FFmpeg not available, video creation skipped. Install FFmpeg to enable video creation.&quot;);<br>            }<br><br>        } catch (Exception e) {<br>            logger.error(&quot;Failed to create video: {}&quot;, e.getMessage(), e);<br>        }<br>    }<br><br>    private void ensureOutputDirectoryExists() throws IOException {<br>        Path outputDir = Paths.get(cachedOutputPath).getParent();<br>        if (outputDir != null) {<br>            Files.createDirectories(outputDir);<br>        }<br>    }<br><br>    private void createVideoWithFFmpeg() throws Exception {<br>        String[] ffmpegCommand = buildFFmpegCommand();<br><br>        logger.debug(&quot;Running FFmpeg command: {}&quot;, String.join(&quot; &quot;, ffmpegCommand));<br><br>        Process process = new ProcessBuilder(ffmpegCommand).start();<br>        int exitCode = process.waitFor();<br><br>        validateVideoCreation(exitCode);<br>    }<br><br>    private String[] buildFFmpegCommand() {<br>        return new String[]{<br>            &quot;ffmpeg&quot;,<br>            &quot;-framerate&quot;, String.valueOf(frameRate),<br>            &quot;-i&quot;, tempDir.toString() + &quot;/&quot; + FRAME_NAME_FORMAT.replace(&quot;%06d&quot;, &quot;%06d&quot;),<br>            &quot;-vf&quot;, &quot;drawtext=text=&#39;&quot; + WATERMARK_TEXT + &quot;&#39;:fontcolor=red:fontsize=24:x=10:y=10:box=1:boxcolor=black@0.5:boxborderw=5&quot;,<br>            &quot;-c:v&quot;, VIDEO_CODEC,<br>            &quot;-preset&quot;, ENCODING_PRESET,<br>            &quot;-crf&quot;, CRF_VALUE,<br>            &quot;-y&quot;, cachedOutputPath<br>        };<br>    }<br><br>    private void validateVideoCreation(int exitCode) {<br>        if (exitCode == 0) {<br>            File videoFile = new File(cachedOutputPath);<br>            if (videoFile.exists() &amp;&amp; videoFile.length() &gt; 0) {<br>                logger.debug(&quot;Video created successfully: {} ({} bytes)&quot;,<br>                        cachedOutputPath, videoFile.length());<br>            } else {<br>                logger.error(&quot;FFmpeg completed but video file is missing or empty&quot;);<br>            }<br>        } else {<br>            logger.error(&quot;FFmpeg process failed with exit code: {}&quot;, exitCode);<br>        }<br>    }<br><br>    private boolean isFFmpegAvailable() {<br>        try {<br>            Process process = new ProcessBuilder(&quot;ffmpeg&quot;, &quot;-version&quot;).start();<br>            return process.waitFor() == 0;<br>        } catch (IOException | InterruptedException e) {<br>            logger.debug(&quot;FFmpeg availability check failed: {}&quot;, e.getMessage());<br>            return false;<br>        }<br>    }<br><br>    // ===== Utility Methods =====<br>    private void cleanupTempFiles() {<br>        if (tempDir == null || !Files.exists(tempDir)) {<br>            return;<br>        }<br><br>        try {<br>            Files.walk(tempDir)<br>                    .sorted((a, b) -&gt; b.compareTo(a)) // Delete files before directories<br>                    .forEach(this::deleteFileQuietly);<br><br>            logger.debug(&quot;Cleaned up temp directory: {}&quot;, tempDir);<br>        } catch (IOException e) {<br>            logger.warn(&quot;Failed to cleanup temp files: {}&quot;, e.getMessage(), e);<br>        }<br>    }<br><br>    private void deleteFileQuietly(Path path) {<br>        try {<br>            Files.deleteIfExists(path);<br>        } catch (IOException e) {<br>            logger.warn(&quot;Failed to delete temp file: {} - {}&quot;, path, e.getMessage());<br>        }<br>    }<br><br>    // ===== Public Getters =====<br>    /**<br>     * Returns the cached output path of the current or last recording.<br>     *<br>     * @return the output path, or null if no recording has been started<br>     */<br>    public String getCachedOutputPath() {<br>        return cachedOutputPath;<br>    }<br>}</pre><h3><strong>Usage in Your Test Framework</strong></h3><h4><strong>Basic Integration</strong></h4><pre>public class LoginTest extends BaseTest {<br>  ScreenRecorder screenRecorder;<br><br>  @BeforeMethod<br>  public void setUp() {<br>    screenRecorder = ScreenRecorder.getInstance();<br>    screenRecorder.startScreenRecording();<br>  }<br><br>  @AfterMethod<br>  public void tearDown() {<br>    screenRecorder.stopRecording();<br>  }<br><br>  @Test<br>  public void testSuccessfulLogin() {<br>    // Navigate<br>    driver.get(&quot;https://example.com/login&quot;);<br><br>    // Your test steps…<br>    loginPage.enterUsername(&quot;testuser&quot;);<br>    loginPage.enterPassword(&quot;password&quot;);<br>    loginPage.clickLogin();<br><br>    // Recording stops automatically in @AfterMethod<br>  }<br>}</pre><h4><strong>Configuration Options</strong></h4><p>Control recording behavior via system properties:</p><pre># Enable recording<br>-DenableRecording=true<br># Run in headless mode<br>-Dheadless=true<br># Specify browser<br>-Dbrowser=chrome</pre><h4><strong>CI/CD Integration</strong></h4><p>In your Jenkins/TeamCity pipeline:</p><pre>mvn test -DenableRecording=true -Dheadless=true -Dbrowser=chrome</pre><p>Videos are automatically:</p><ul><li>Generated with test method names</li><li>Saved in <strong>target/video/</strong> directory</li></ul><h3><strong>Performance Considerations</strong></h3><h4><strong>Memory Usage</strong></h4><ul><li><strong>10 FPS recording</strong>: ~600 KB/minute for 1920x1080 screenshots</li><li><strong>Temporary storage</strong>: Automatically cleaned up after video creation</li><li><strong>Background processing</strong>: Screenshots captured on a separate thread</li></ul><h4><strong>Storage Optimization</strong></h4><ul><li><strong>Smart frame rates</strong>: 5–10 FPS are sufficient for debugging</li><li><strong>Compression</strong>: FFmpeg with ultrafast preset for CI environments</li><li><strong>Selective recording</strong>: Only record on test failures (configurable)</li></ul><pre>// Record only on failures<br>if (enableRecording &amp;&amp; testFailed) {<br>  String videoName = &quot;Test Recording (FAILED)&quot;;<br>  AllureReporter.attachVideo(videoPath, videoName);<br>}</pre><h3><strong>Troubleshooting Common Issues</strong></h3><p><strong>1. “FFmpeg not found”</strong></p><pre># Install FFmpeg in CI environment<br>apt-get update &amp;&amp; apt-get install -y ffmpeg # Ubuntu/Debian<br>yum install ffmpeg # CentOS/RHEL</pre><p><strong>2. “Out of disk space”</strong></p><ul><li>Reduce frame rate: `frameRate = 5`</li><li>Implement cleanup policies</li><li>Use temporary directories with automatic cleanup</li></ul><h3><strong>Real-World Results</strong></h3><p>After implementing this solution across multiple projects:</p><p><strong>Before</strong></p><ul><li>❌ Hours of debugging failed CI tests</li><li>❌ Dependency conflicts in environments</li><li>❌ Recording failures in headless mode</li><li>❌ Platform-specific setup requirements</li></ul><p><strong>After</strong></p><ul><li>✅ Shorter time to identify the root cause from the video</li><li>✅ Zero dependency issues</li><li>✅ 100% success rate in headless CI environments</li><li>✅ Identical setup across all platforms</li></ul><h3><strong>Advanced Features You Can Add</strong></h3><ol><li><strong>Smart Recording Triggers: </strong>Only record when the test fails</li><li><strong>Custom Watermarks: </strong>Add test metadata to videos, e.g., test name, browser, environment</li><li><strong>Parallel Test Support: </strong>Thread-safe recording for parallel execution</li><li><strong>Attach video to HTML reports</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fTCwo7lPRq0lPOineK8xNg.png" /></figure><h3><strong>The Bottom Line</strong></h3><p>Building a custom screen recorder might seem like overkill, but when you’re dealing with:</p><ul><li>Complex CI/CD environments</li><li>Multiple browser configurations</li><li>Headless execution requirements</li><li>Zero tolerance for debugging friction</li></ul><p>The investment pays off immediately. This lightweight solution has eliminated debugging headaches while maintaining a minimal footprint.</p><h3><strong>Complete Implementation</strong></h3><p>The full source code for this screen recorder is available on GitHub: <a href="https://github.com/wavda/selenium-testng">https://github.com/wavda/selenium-testng</a>.</p><p>Key files:</p><ul><li>ScreenRecorder.java — Core recording logic</li><li>BaseTest.java — TestNG integration</li><li>AllureReporter.java — Report integration</li></ul><p>Have you struggled with screen recording in headless environments? Share your experiences in the comments below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=116cf1884ccf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Seamlessly Integrate Appium with Xcode Emulator for iOS Testing]]></title>
            <link>https://anivaz.medium.com/how-to-seamlessly-integrate-appium-with-xcode-emulator-for-ios-testing-3da72b461208?source=rss-beb8620860f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/3da72b461208</guid>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[appium]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[simulator]]></category>
            <dc:creator><![CDATA[Wavda Aniva]]></dc:creator>
            <pubDate>Thu, 20 Jul 2023 11:01:39 GMT</pubDate>
            <atom:updated>2023-07-20T11:01:39.135Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Seamlessly Integrate Appium with Xcode Simulator for iOS Testing</h3><p>Are you looking for a way to streamline your iOS testing process? If so, integrating Appium with the Xcode emulator is a great way to automate your testing and ensure your app runs smoothly on different iOS devices. By combining the power of Appium and the Xcode emulator, you can quickly and easily set up your test environment and run tests on a wide range of iOS devices. In this article, we’ll show you how to seamlessly integrate Appium with the Xcode emulator for iOS testing, so you can improve your app’s quality and ensure a great user experience.</p><h3>Part 1: Installations</h3><ol><li>Install <a href="https://apps.apple.com/us/app/xcode/id497799835">Xcode</a> on your Mac through the App Store.</li><li>Install <a href="https://docs.brew.sh/Installation">Homebrew</a> if you don’t have it already. You can install it by running the following command in your terminal:</li></ol><pre>/bin/bash -c &quot;$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)&quot;</pre><p>3. Install <a href="https://nodejs.org/en/download">Node.js</a> using the following commands in your terminal:</p><pre>brew install node</pre><p>4. Install <a href="https://appium.io/docs/en/2.0/quickstart/install/">Appium</a> using the following commands in your terminal:</p><pre>npm install -g appium</pre><p>5. Install Appium Doctor. It checks your system and tells you how to set up Appium. You can install it by running the following command in your terminal:</p><pre>npm install -g appium-doctor</pre><p>6. Run Appium Doctor to check if everything is set up correctly. You can run it by running the following command in your terminal:</p><pre>appium-doctor</pre><p>If you see any issues, follow the instructions given by the Appium Doctor to fix them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R6QK9EPV41G6x7IDTz-ldw.png" /></figure><h3>Part 2: Emulator Setup</h3><p>1. Launch the Xcode emulator by running the following command in your terminal, and then install your application:</p><pre>open /Applications/Xcode.app/Contents/Developer/Applications/Simulator.app</pre><p>2. Install your application on the device emulator. In this example, we’ll use the following Sauce Labs Demo application for testing: <a href="https://github.com/saucelabs/sample-app-mobile/releases">https://github.com/saucelabs/sample-app-mobile/releases</a></p><p>3. Get the list of available devices information, such as their deviceName<strong>, </strong>platformVersion<strong>, </strong>and<strong> </strong>udid<strong> </strong>using the following command:</p><pre>xcrun xctrace list devices</pre><p>4. Get the application’s bundleId based on the list of installed applications for a specific device udid<strong> </strong>using the following command:</p><pre>xcrun simctl listapps device-udid-goes-here</pre><h3>Part 3: Getting Element Locator using Appium Inspector</h3><p>1. Install and run Appium Inspector: <a href="https://github.com/appium/appium-inspector/releases">https://github.com/appium/appium-inspector/releases</a>.</p><p>2. Set the remote path to “/wd/hub”</p><p>3. Set the desired capabilities, e.g.</p><pre>{<br>  &quot;platformName&quot;: &quot;iOS&quot;,<br>  &quot;appium:platformVersion&quot;: &quot;16.4&quot;,<br>  &quot;appium:deviceName&quot;: &quot;iPhone 14 Pro&quot;,<br>  &quot;appium:automationName&quot;: &quot;XCUITest&quot;,<br>  &quot;appium:udid&quot;: &quot;auto&quot;,<br>  &quot;appium:bundleId&quot;: &quot;com.saucelabs.SwagLabsMobileApp&quot;,<br>  &quot;appium:noReset&quot;: &quot;true&quot;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E6sS1ZtLBaNblVtBXjQvnw.png" /></figure><p>4. Start Appium by running the following command in your terminal:</p><pre>appium --base-path /wd/hub --allow-cors</pre><p>5. Click on “Start Session” in the Appium Inspector. You should be able to start inspecting the element locators as follows once Appium Inspector has successfully connected to the simulator:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yv7i3uTeijwoQjX1WHoDMw.png" /></figure><h3>Part 4: Running Automated Tests</h3><p>Create a new Appium project in your preferred programming language and specify the desired capabilities to launch the Xcode emulator. For example, in JavaScript using WebdriverIO, you can find the step-by-step instructions in this article, <a href="https://medium.com/@anivaz/streamlining-mobile-app-testing-with-webdriverio-and-appium-777310a3691b">Streamlining Mobile App Testing with WebdriverIO and Appium</a>.</p><p>Add the following settings to your test project configuration file:</p><pre>// ...<br><br>runner: &#39;local&#39;,<br>path: &#39;/wd/hub&#39;,<br>port: 4723,<br>allowCors: true,<br><br>services: [<br>    [&#39;appium&#39;, {<br>        command: &#39;appium&#39;,<br>        logPath: &#39;./logs/&#39;<br>    }]<br>],<br><br>capabilities: [{<br>    &#39;appium:platformName&#39;: &#39;iOS&#39;,<br>    &#39;appium:automationName&#39;: &#39;XCUITest&#39;,<br>    &#39;appium:platformVersion&#39;: &#39;16.4&#39;,<br>    &#39;appium:deviceName&#39;: &#39;iPhone 14 Pro&#39;,<br>    &#39;appium:udid&#39;:&#39;auto&#39;,<br>    &#39;appium:bundleId&#39;: &#39;com.saucelabs.SwagLabsMobileApp&#39;,<br>    &#39;appium:noReset&#39;: true<br>}],<br><br>// ...</pre><p>Note that you’ll need to replace the desired capabilities with your own values.</p><p>That’s it! You should now be able to run your Appium tests on the Xcode emulator.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3da72b461208" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplifying 2FA Testing with Node.js and Gmail API: Tools and Libraries for Easier Test Automation]]></title>
            <link>https://anivaz.medium.com/simplifying-2fa-testing-with-node-js-and-gmail-api-tools-and-libraries-for-easier-test-automation-9c92b8484d7f?source=rss-beb8620860f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c92b8484d7f</guid>
            <category><![CDATA[gmail]]></category>
            <category><![CDATA[e2e-testing]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[google-api]]></category>
            <category><![CDATA[webdriverio]]></category>
            <dc:creator><![CDATA[Wavda Aniva]]></dc:creator>
            <pubDate>Wed, 17 May 2023 13:01:47 GMT</pubDate>
            <atom:updated>2023-05-19T12:47:42.712Z</atom:updated>
            <content:encoded><![CDATA[<p>Two-factor authentication (2FA) is a crucial security measure that protects sensitive data and resources from unauthorized access. Testing 2FA in an automated way can be challenging, as it requires the integration of multiple components, including email providers and authentication mechanisms. In this article, we will explore how to simplify 2FA testing using Node.js and the Gmail API, with the help of some popular libraries and tools.</p><h3>Pre-requisites</h3><ol><li><a href="https://nodejs.org/en/download/">Node.js</a> (version 12 or later)</li><li>npm (version 6 or later)</li><li>Source code editor e.g. <a href="https://code.visualstudio.com/download">Visual Studio Code</a></li></ol><h3>Part 1: Setting Up the Gmail API in Google Cloud</h3><p>Before we can use the Gmail API to retrieve 2FA messages, we need to set up a Google Cloud project and enable the Gmail API. Here are the steps to follow:</p><ol><li>Go to the <a href="https://console.cloud.google.com/">Google Cloud Console</a> and create a new project.</li><li>Enable the Gmail API by going to <strong>APIs &amp; Services</strong> &gt; <strong>Library </strong>on the side menu. Search for “Gmail API” and click on the result.</li><li>Click on the “<strong>+ ENABLE</strong>” button to enable the API for your project.</li><li>Create a new OAuth 2.0 client ID by going to <strong>APIs &amp; Services</strong> &gt; <strong>Credentials</strong> and clicking the “<strong>+ CREATE CREDENTIALS</strong>” button. Choose “<strong>OAuth client ID</strong>” as the type of credentials.</li><li>Choose “<strong>Desktop app</strong>” as the application type and give it a name.</li><li>Download the client&#39;s secret JSON file by clicking on the download button next to the newly created client ID.</li><li>Save the client&#39;s secret file securely, as it contains sensitive information that should not be shared. In this example, we’ll name the .json file as “<strong>google-credentials.json”</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*byc8-K9cLeHZ9foUrMrBVA.png" /></figure><p>The .json file containing the credentials should look something like this:</p><pre>{<br>  &quot;installed&quot;: {<br>      &quot;client_id&quot;: &quot;...&quot;,<br>      &quot;project_id&quot;: &quot;...&quot;,<br>      &quot;auth_uri&quot;: &quot;https://accounts.google.com/o/oauth2/auth&quot;,<br>      &quot;token_uri&quot;: &quot;https://oauth2.googleapis.com/token&quot;,<br>      &quot;auth_provider_x509_cert_url&quot;: &quot;https://www.googleapis.com/oauth2/v1/certs&quot;,<br>      &quot;client_secret&quot;: &quot;...&quot;,<br>      &quot;redirect_uris&quot;: [<br>          &quot;...&quot;<br>      ]<br>  }<br>}</pre><p>With the Gmail API set up, we can now retrieve 2FA messages and automate our testing process.</p><h3>Part 2: Setup Test Project</h3><p>1. Create a new project folder, for example, called “<strong>test-project”.</strong></p><p>2. Run the following command through the terminal or command line within your project directory to initiate the project:</p><pre>npm init -y</pre><p>3. We’ll use the Google API to get the OTP code from the email and use WebdriverIO as a sample for the E2E test. Run the following command to install dependencies.</p><pre>npm install --save-dev fs googleapis @google-cloud/local-auth webdriverio</pre><p>4. Proceed with configuring your test project. In this article, we will use WebdriverIO as an example of an end-to-end (E2E) testing framework. If you are unfamiliar with setting up E2E tests using WebdriverIO, you can gain a comprehensive understanding by referring to this article, “<a href="https://anivaz.medium.com/webdriverio-and-page-object-model-designing-scalable-test-suites-344d8e55c24b">WebdriverIO and Page Object Model: Designing Scalable Test Suites.</a>” The article provides detailed step-by-step instructions to guide you through the setup process.</p><h3>Part 3: Get the Gmail Message Content for the OTP</h3><p>We will use “<strong>googleapis</strong>” dependency to simulate retrieving a 2FA message from Gmail and extracting the OTP from the message content. Here’s how to do it:</p><pre>const fs = require(&#39;fs&#39;).promises;<br>const path = require(&#39;path&#39;);<br>const process = require(&#39;process&#39;);<br>const { authenticate } = require(&#39;@google-cloud/local-auth&#39;);<br>const { google } = require(&#39;googleapis&#39;);<br><br>const SCOPES = [&#39;https://www.googleapis.com/auth/gmail.readonly&#39;];<br>const TOKEN_PATH = path.join(process.cwd(), &#39;google-token.json&#39;);<br>const CREDENTIALS_PATH = path.join(process.cwd(), &#39;google-credentials.json&#39;);<br><br>class Gmail {<br>  async retrieveOtp() {<br>    const auth = await this.authorize();<br>    const list_message = await this.getListMessage(auth, &#39;OTP&#39;);<br>    const fullMessage = await this.getMessage(auth, list_message);<br>    return fullMessage.data.snippet;<br>  }<br><br>  async authorize() {<br>    var client = await this.loadSavedCredentialsIfExist();<br>    if (client) {<br>      return client;<br>    }<br>    client = await authenticate({<br>      scopes: SCOPES,<br>      keyfilePath: CREDENTIALS_PATH,<br>    });<br>    if (client.credentials) {<br>      await this.saveCredentials(client);<br>    }<br>    return client;<br>  }<br><br>  async loadSavedCredentialsIfExist() {<br>    try {<br>      const content = await fs.readFile(TOKEN_PATH);<br>      const credentials = JSON.parse(content);<br>      return google.auth.fromJSON(credentials);<br>    } catch (err) {<br>        return null;<br>    }<br>  }<br><br>  async saveCredentials(client) {<br>    const content = await fs.readFile(CREDENTIALS_PATH);<br>    const keys = JSON.parse(content);<br>    const key = keys.installed || keys.web;<br>    const payload = JSON.stringify({<br>      type: &#39;authorized_user&#39;,<br>      client_id: key.client_id,<br>      client_secret: key.client_secret,<br>      refresh_token: client.credentials.refresh_token,<br>    });<br>    await fs.writeFile(TOKEN_PATH, payload);<br>  }<br><br>  async getListMessage(auth, search_keyword) {<br>    const gmail = google.gmail({ version: &#39;v1&#39;, auth, timeout: 210000 });<br>    return await gmail.users.messages.list({<br>      userId: &#39;me&#39;,<br>      q: search_keyword<br>    });<br>  }<br><br>  async getMessage(auth, list_message) {<br>    const gmail = google.gmail({ version: &#39;v1&#39;, auth, timeout: 210000 });<br>    return await gmail.users.messages.get({<br>      userId: &#39;me&#39;,<br>      id: list_message.data.messages[0].id,<br>      format: &#39;full&#39;<br>    });<br>  }<br>}<br><br>module.exports = { Gmail }</pre><p>We’ll name the file above as “<strong>gmail-api.js”, </strong>which should perform:</p><ol><li>retrieveOtp(): This method retrieves the OTP (One-Time Password) from a Gmail message. It first authorizes the application, then retrieves the list of messages containing the keyword &#39;OTP&#39;, and finally fetches the full content of the selected message. The OTP is extracted from the message&#39;s snippet and returned.</li><li>authorize(): This method handles the authorization process for accessing the Gmail API. It first attempts to load saved credentials, if they exist. If not, it prompts the user to authenticate and generate new credentials. The generated credentials are then saved for future use.</li><li>loadSavedCredentialsIfExist(): This method attempts to load previously saved credentials from a token file. If the file exists, it reads its content, parses it, and returns the corresponding Google authentication client.</li><li>saveCredentials(client): This method saves the credentials obtained from the authentication process. It reads the credentials file, extracts the necessary information, including the client ID, client secret, and refresh token from the client object, and saves them in a token file for future use.</li><li>getListMessage(auth, search_keyword): This method retrieves a list of Gmail messages based on the provided search keyword. It utilizes the authorized client to make a request to the Gmail API and returns the response, which includes a list of messages matching the search criteria.</li><li>getMessage(auth, list_message): This method fetches the full content of a specific Gmail message. It takes the authorized client and the list of messages obtained from getListMessage() as input. It retrieves the message using the message ID from the first item in the list and returns the full message content.</li></ol><h3>Part 4: Using WebdriverIO for the End-to-End Test Scenario</h3><p>WebdriverIO is widely utilized for automating browsers within Node.js applications. It offers the capability to mimic a user’s actions, such as logging into an application that has two-factor authentication (2FA) enabled, and successfully completing the authentication process by utilizing the OTP code. Here’s an example of the test, which we’ll name “<strong>login.spec.js</strong>”:</p><pre>const { Gmail } = require(&#39;gmail-api&#39;);<br>const { remote } = require(&#39;webdriverio&#39;);<br>const assert = require(&#39;assert&#39;);<br>const gmail = new Gmail();<br><br>async function loginWith2fa(username, password) {<br>  const browser = await remote({<br>    capabilities: {<br>      browserName: &#39;chrome&#39;<br>    }<br>  });<br><br>  await browser.url(https://medium.com/&#39;https://myapp.com/login&#39;);<br>  await browser.$(&#39;#username&#39;).setValue(username);<br>  await browser.$(&#39;#password&#39;).setValue(password);<br>  await browser.$(&#39;#login-button&#39;).click();<br><br>  const otp = await gmail.retrieveOtp();<br>  await browser.$(&#39;#otp-code&#39;).setValue(otp);<br>  await browser.$(&#39;#submit-button&#39;).click();<br><br>  const pageTitle = await browser.getTitle();<br>  assert.equal(pageTitle, &#39;MyApp - Dashboard&#39;);<br><br>  await browser.deleteSession();<br>}</pre><p>Now you can run your test.</p><pre>wdio run ./wdio.conf.js</pre><h3>Conclusion</h3><p>In this article, we have explored how to simplify 2FA testing using Node.js and the Gmail API, with the help of some popular libraries and tools. We have seen how to set up the Gmail API in Google Console, use Supertest to retrieve the OTP code from the email message, and use WebdriverIO to simulate the login scenario and complete the authentication process. With these techniques, you can automate your 2FA testing and ensure the security of your applications and resources.</p><h3>Reference</h3><ul><li><a href="https://developers.google.com/gmail/api/quickstart/nodejs">https://developers.google.com/gmail/api/quickstart/nodejs</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c92b8484d7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streamlining Mobile App Testing with WebdriverIO and Appium]]></title>
            <link>https://anivaz.medium.com/streamlining-mobile-app-testing-with-webdriverio-and-appium-777310a3691b?source=rss-beb8620860f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/777310a3691b</guid>
            <category><![CDATA[webdriverio]]></category>
            <category><![CDATA[mobile-testing]]></category>
            <category><![CDATA[android-studio]]></category>
            <category><![CDATA[appium]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Wavda Aniva]]></dc:creator>
            <pubDate>Sat, 15 Apr 2023 00:06:46 GMT</pubDate>
            <atom:updated>2023-04-15T02:58:34.040Z</atom:updated>
            <content:encoded><![CDATA[<p>To ensure a high-quality application, testing is an essential phase in software development. Yet, testing mobile applications can be challenging for testers, especially when the application needs to be tested to see if it is working correctly across multiple platforms, operating systems, and devices.</p><p>Powerful tools like WebdriverIO and Appium can greatly improve mobile app testing and build effective test automation frameworks. In this article, we’ll look at how to use WebdriverIO with Appium to speed up mobile app testing.</p><h3>Benefits of Using WebdriverIO and Appium for Mobile App Testing</h3><p>WebdriverIO and Appium are powerful tools that can help streamline mobile app testing by creating efficient and effective test automation frameworks. The advantages of using WebdriverIO and Appium for mobile app testing include the following:</p><ol><li><strong>Efficient testing</strong>: WebdriverIO and Appium enable mobile app testing across various devices, platforms, and operating systems. This lowers testing time and effort, resulting in faster feedback on issues.</li><li><strong>Cross-platform testing</strong>: it is supported by WebdriverIO and Appium, allowing testers to test mobile applications on different platforms such as Android and iOS with a single test script.</li><li>WebdriverIO and Appium <strong>support several programming languages</strong>, including JavaScript, Python, and Ruby, which makes it simpler for developers and testers to develop test scripts.</li></ol><h3>Pre-requisites</h3><p>Before setting up WebdriverIO and Appium for mobile app testing, ensure that the following prerequisites are met:</p><ol><li>A local machine with Node.js installed.</li><li>Appium server installed.</li><li>Android or iOS device connected to the local machine.</li><li>An emulator or simulator is installed.</li></ol><p>You can also find a step-by-step guide for setting up the above pre-requisites in this article: https://link.medium.com/N7vgleuv0yb</p><h3>Setting up WebdriverIO and Appium for Mobile App Testing</h3><p>We’ll proceed with setting up WebdriverIO and Appium for mobile app testing with the following steps:</p><h4><strong>Step 1: </strong>Initiate Project</h4><p>Run the following command to start a node.js project within your test project directory. In this example, we’ll create the project within a folder called <strong>wdio-appium-test.</strong></p><pre>npm init -y</pre><h4><strong>Step 2: </strong>Install Dependencies</h4><p>Install Appium, WebdriverIO CLI, and Allure CLI dependencies with the following command:</p><pre>npm install @wdio/cli allure-commandline --save-dev</pre><h4><strong>Step 3: Configure Test Setup</strong></h4><p>Run the following command to configure your test:</p><pre>npx wdio config</pre><p>With the command above, a wizard will be executed, which will require you to answer a couple of questions. In this example, we’ll configure the test setup so that it’ll</p><ul><li>be launched locally</li><li>have automation backend located locally</li><li>run using the <strong>mocha </strong>framework</li><li>run without compiler</li><li>use autogenerated <strong>page objects</strong> and <strong>test</strong> files</li><li>use test reporter <strong>spec </strong>and <strong>allure</strong></li><li>use <strong>wait-for</strong> plugin</li><li>use <strong>chromedriver </strong>service</li></ul><h4>Step 4: <strong>Setup Service and Capabilities for Appium</strong></h4><p>Add capabilities configuration to your <strong>wdio.conf.js</strong> file, for example:</p><pre>// ...<br><br>services: [<br>    [&#39;appium&#39;, {<br>        command: &#39;appium&#39;,<br>        logPath: &#39;./logs/&#39;<br>    }]<br>],<br><br>capabilities: [{<br>      platformName: &#39;Android&#39;,<br>      platformVersion: &#39;13.0&#39;,<br>      deviceName: &#39;Pixel_4&#39;,<br>      udid: &#39;emulator-5554&#39;,<br>      autoGrantPermissions: true,<br>      app: &#39;apk/NativeDemoApp.apk&#39;,<br>      automationName: &#39;UiAutomator2&#39;,<br>      appPackage: &#39;com.wdiodemoapp&#39;,<br>      appActivity: &#39;com.wdiodemoapp.MainActivity&#39;<br>  }],<br><br>// ...</pre><p>This capabilities configuration will allow you to test a <a href="https://github.com/webdriverio/native-demo-app/releases">WebdriverIO demo app file</a> located within the folder C<strong>:\demo\wdio-appium\apk</strong> using the Android emulator we created earlier in this article: https://link.medium.com/N7vgleuv0yb</p><h4><strong>Step 5: Configure Test Report</strong></h4><p>Add the following configuration to your <strong>wdio.conf.js</strong> file, which will allow you to get logs for each step of the test as well as screenshots of failing tests:</p><pre>reporters: [&#39;spec&#39;, [&#39;allure&#39;, {<br>    outputDir: &#39;./allure-results&#39;,<br>    disableWebdriverStepsReporting: true,<br>    disableWebdriverScreenshotsReporting: false,<br>}]],</pre><h4>Step 6: Setup Test Execution Script</h4><p>Add the following script to your <strong>package.json </strong>file:</p><pre>&quot;scripts&quot;: {<br>  &quot;test&quot;: &quot;npx wdio wdio.conf.js&quot;,<br>  &quot;report&quot;: &quot;npx allure generate allure-results --clean &amp;&amp; npx allure open&quot;<br>},</pre><h3>Write Test Script</h3><p>Once we have set up WebdriverIO with Appium, we can start writing our page objects and test cases. Let’s start with a simple test case that signs up a new account on the demo app and verifies that a successful message is displayed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*PZC4JRLO8Vrb6swbPGCjdg.png" /><figcaption>WebdriverIO Demo Application</figcaption></figure><h4>Step 1: Creating Page Objects</h4><p>Page objects are classes that represent the different pages of our mobile website. They encapsulate the page elements and the actions that can be performed on those elements.</p><p>Let’s create a page object in <strong>test/pageobjects/page.js </strong>for the navigation menu that is shared across the demo application.</p><pre>module.exports = class Page {<br>    get loginWidget() {<br>        return $(&#39;//*[@content-desc=&quot;Login&quot;]&#39;);<br>    }<br>}</pre><p>Now, let’s create a page object for the login page within <strong>test/pageobjects/login.page.js</strong>.</p><pre>const Page = require(&#39;./page&#39;);<br><br>class LoginPage extends Page {<br>    get btnSignUpContainer () {<br>        return $(&#39;//*[@content-desc=&quot;button-sign-up-container&quot;]&#39;);<br>    }<br><br>    get inputEmail () {<br>        return $(&#39;~input-email&#39;);<br>    }<br><br>    get inputPassword () {<br>        return $(&#39;~input-password&#39;);<br>    }<br><br>    get inputRepeatPassword () {<br>        return $(&#39;~input-repeat-password&#39;);<br>    }<br><br>    get btnSignUp () {<br>        return $(&#39;//*[@content-desc=&quot;button-SIGN UP&quot;]&#39;);<br>    }<br><br>    get popupSignupSuccessMessage() {<br>        return $(&#39;//*[@resource-id=&quot;android:id/message&quot;]&#39;);<br>    }<br><br>    async signUp (email, password) {<br>        await super.loginWidget.click();<br>        await this.btnSignUpContainer.click();<br>        await this.inputEmail.setValue(email);<br>        await this.inputPassword.setValue(password);<br>        await this.inputRepeatPassword.setValue(password);<br>        await this.btnSignUp.click();<br>    }<br>}<br><br>module.exports = new LoginPage();</pre><p>In the above code, we have defined a LoginPage class along with the element locators on the login page related to the sign-up process.</p><p>We have also defined a signUp() method that performs the sign-up process, starting with clicking the button to open the sign-up form, inputting values into the required fields (email, password, password confirmation), and clicking the sign-up button.</p><h4>Step 2: Writing Test Cases</h4><p>Now we can start writing our test cases with our page object in place.</p><p>Let’s write our test case to use the LoginPage page object.</p><pre>const LoginPage = require(&#39;../pageobjects/login.page&#39;)<br><br>describe(&#39;Login/Sign Up Form&#39;, () =&gt; {<br>    it(&#39;should signup with valid credentials&#39;, async () =&gt; {<br>        await LoginPage.signUp(&#39;testing123@mailnator.com&#39;, &#39;SuperSecretPassword!&#39;)<br>        await expect(LoginPage.popupSignupSuccessMessage).toBeExisting()<br>        await expect(LoginPage.popupSignupSuccessMessage).toHaveTextContaining(&#39;You successfully signed up!&#39;)<br>    })<br>})</pre><p>In the above code, we have created an instance of the LoginPage class and used its signUp() method to perform the sign-up process using the email and password as the parameter.</p><p>We have also added the expect assertion, which will check if the popupSignupSuccessMessage element defined in LoginPage exists and contains the text “You successfully signed up!”.</p><h3>Running the Test Cases</h3><p>To run the test cases, we need to execute the following command, which we have defined in the script within the <strong>package.json </strong>file:</p><pre>npm test</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VIF6InM2DlgW9s2ebtJJRA.png" /><figcaption>Running test command</figcaption></figure><p>Once the test execution is complete, proceed with generating the HTML report using Allure with the following command:</p><pre>npm run report</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vja2stkyit3wBp_aE-QkQg.png" /><figcaption>Running generate report command</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GjODqPa6ZR9sBVMGaoreDw.png" /><figcaption>Allure HTML Report</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=777310a3691b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Set Up Appium with Android Studio for Mobile App Testing]]></title>
            <link>https://anivaz.medium.com/how-to-set-up-appium-with-android-studio-for-mobile-app-testing-a300b7910364?source=rss-beb8620860f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/a300b7910364</guid>
            <category><![CDATA[emulator]]></category>
            <category><![CDATA[appium-inspector]]></category>
            <category><![CDATA[android-studio]]></category>
            <category><![CDATA[mobile-testing]]></category>
            <category><![CDATA[appium]]></category>
            <dc:creator><![CDATA[Wavda Aniva]]></dc:creator>
            <pubDate>Sat, 15 Apr 2023 00:01:38 GMT</pubDate>
            <atom:updated>2025-08-18T09:55:34.604Z</atom:updated>
            <content:encoded><![CDATA[<p>As the use of mobile applications grows, so does the demand for mobile app testing. Because of its flexibility, support for multiple programming languages, and cross-platform capabilities, Appium, an open-source tool, is widely used for mobile app testing.</p><p>This article will guide you through setting up Android Studio and Appium for mobile app testing, whether you are a seasoned developer, tester, or just getting started. Now let’s get going!</p><h3>Pre-requisites</h3><ol><li>Node.js installed: <a href="https://nodejs.org/en/download">https://nodejs.org/en/download</a></li><li>Android Studio installed: <a href="https://developer.android.com/studio/install">https://developer.android.com/studio/install</a></li></ol><h3>Step 1: Install JDK</h3><p>1. Go to the <a href="https://www.oracle.com/java/technologies/downloads/">Oracle website</a> and download the latest JDK installer for your operating system.</p><p>2. Run the installer and follow the prompts to complete the installation.</p><p>3. Set the JAVA_HOME environment variable to the JDK installation directory after installation. For example, if you installed JDK in <strong>C:\Program Files\Java\jdk-19</strong>, set <strong>JAVA_HOME </strong>to <strong>C:\Program Files\Java\jdk-19</strong>.</p><p>4. Add the JDK bin directory to your system’s <strong>PATH </strong>environment variable. For example, if you installed JDK in <strong>C:\Program Files\Java\jdk-19</strong>, add <strong>C:\Program Files\Java\jdk-19\bin</strong> to the <strong>PATH </strong>environment variable.</p><h3>Step 2: Setup Emulator with Android Studio</h3><p>1. <strong>Install Android SDK</strong>: Once Android Studio is installed, open it and follow the setup wizard to install the Android SDK (Software Development Kit) through <strong>More Actions &gt; SDK Manager</strong>. This is a set of tools that enable you to run the emulator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*5wtkjJvedMxDccB1OmDGJA.png" /></figure><p>Install the Android version that you’d like to install on your emulator under <strong>SDK Platform</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*76eIAaoTJPzpFItEv0DGXQ.png" /></figure><p>Install <strong>SDK Tools </strong>such as <strong>Intel processor with Intel HAXM</strong> (for faster emulation performance)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*GF2AkECWnQaRkckX8CLB2Q.png" /><figcaption>SDK Tools</figcaption></figure><p>4. Add the Android SDK directory to your system’s <strong>ANDROID_HOME </strong>environment variable. For example, if the Android SDK Location in Android Studio is <strong>C:\Users\Administrator\AppData\Local\Android\Sdk</strong>, add <strong>C:\Users\Administrator\AppData\Local\Android\Sdk</strong> to the <strong>ANDROID_HOME </strong>environment variable.</p><p>5. An <strong>Android Virtual Device (AVD)</strong> is an emulator that allows you to test your apps without using a physical device. To set up an AVD, open Android Studio, click on the <strong>More Actions &gt; Virtual Device Manager </strong>button, and proceed with the virtual device creation by selecting the hardware and system image. You can also refer to this document for a more detailed guideline <a href="https://developer.android.com/studio/run/managing-avds">https://developer.android.com/studio/run/managing-avds</a>.</p><p>6. <strong>Run the emulator</strong>: Click on the “Run” button to start the AVD on the Virtual Device Manager page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*LK_pu7gFhJGnh4OfIhRZ6A.png" /></figure><h3>Step 3: Setup Appium</h3><p>1. <strong>Install Appium</strong>: Open a terminal window (or command prompt on Windows) and run the following command to install Appium using NPM. This will install the latest version of Appium globally on your computer.</p><pre>npm install -g appium</pre><p>2. <strong>Install Appium Doctor</strong>: Appium Doctor is a command-line tool that helps you diagnose and fix common Appium installation issues. To install Appium Doctor, run the following command:</p><pre>npm install -g @appium/doctor</pre><p>3. <strong>Check Appium installation</strong>: Run the following command to check that Appium is installed and running correctly. This should output the version of Appium that you just installed.</p><pre>appium --version</pre><p>4. <strong>Run Appium Doctor</strong>: The following command will perform a number of tests to ensure that all prerequisites and dependencies are met before running Appium. It helps in spotting potential issues that can arise when running Appium and provides instructions on how to fix them.</p><pre>appium-doctor</pre><h3><strong>Step 4: Setup Appium Inspector</strong></h3><ol><li>Download and install Appium Desktop from the official website (<a href="https://github.com/appium/appium-desktop/releases">https://github.com/appium/appium-desktop/releases</a>). Choose the appropriate version for your operating system.</li><li>Once the installation is complete, open Appium Inspector.</li><li>Click on the “Start Inspector Session” button located in the top left corner of the window.</li><li>In the “Desired Capabilities” section, enter the capabilities required to connect to the device. Note: The values for “deviceName”, “appPackage”, and “appActivity” may vary depending on the device and the application you are testing. For example, if you want to connect to an Android emulator, enter the following:</li></ol><pre>{<br>  &quot;platformName&quot;: &quot;Android&quot;,<br>  &quot;deviceName&quot;: &quot;emulator-5554&quot;,<br>  &quot;appPackage&quot;: &quot;com.android.settings&quot;,<br>  &quot;appActivity&quot;: &quot;.Settings&quot;<br>}</pre><p>For other desired capabilities for your emulator, you can refer to: <a href="https://appium.io/docs/en/writing-running-appium/caps/">https://appium.io/docs/en/writing-running-appium/caps/</a></p><h3>Step 5: Getting Element Locators from Your App</h3><p>1. Open a new terminal window and run the following command to start the Appium server. This will start the Appium server on the default port (4723).</p><pre>appium</pre><p>2. Start your device emulator in Android Studio.</p><p>3. Click on the “Start Session” button on Appium Inspector</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W0tRjZOJ8F-fK78f2VmlmA.png" /></figure><p>After clicking on “Start Session&quot;, you will see a screen showing the device’s screen and a tree of elements. The Appium Inspector will display the element’s properties, including its ID, text, class, and more attributes. You can also interact with the device by tapping, swiping, or scrolling using the controls located on the highlighted menus in the screenshot below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ljnBqoQmEPmQkfiaz1mObw.png" /></figure><h3>Step 6: Write and Run Your Test</h3><p>Use your preferred programming language and testing framework to create a test script. Specify the desired capabilities for your test in your script, such as device type, platform version, and app path.</p><p>Run the test script through your preferred testing framework once it’s completed. Connect to the Appium server and run the specified test on the connected device or emulator.</p><p>We’ll discuss more detail on writing and running test scripts using Appium in the upcoming article: https://link.medium.com/0JuXh7nv0yb</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a300b7910364" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating End-to-End Tests for a Web App with Cypress]]></title>
            <link>https://anivaz.medium.com/creating-end-to-end-tests-for-a-web-app-with-cypress-3f3890285578?source=rss-beb8620860f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f3890285578</guid>
            <category><![CDATA[e2e-testing]]></category>
            <category><![CDATA[web-testing]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[allure]]></category>
            <category><![CDATA[cypress]]></category>
            <dc:creator><![CDATA[Wavda Aniva]]></dc:creator>
            <pubDate>Sat, 08 Apr 2023 00:01:49 GMT</pubDate>
            <atom:updated>2023-04-08T00:01:49.994Z</atom:updated>
            <content:encoded><![CDATA[<p>End-to-end testing is an essential phase in the software development process since it ensures that all of a web app’s components are functioning properly. Programmers can create automated tests that simulate real user interactions and validate intended results using this popular testing framework from Cypress. This article will show you how to create end-to-end tests for a web application using Cypress.</p><h3><strong>Pre-requisites</strong></h3><ol><li><a href="https://nodejs.org/en/download/">Node.js</a> installed</li><li>A source code editor e.g. <a href="https://code.visualstudio.com/download">Visual Studio Code</a></li></ol><h3>Initial Setup</h3><p>Before you start writing tests with Cypress, you need to set up a new Cypress project. To do this, you need to have Node.js installed on your machine. Once you have Node.js installed, follow these steps:</p><p><strong>Step 1: </strong>Create a new folder for your Cypress project, e.g., cypress-web-test</p><p><strong>Step 2: </strong>Navigate to the new folder and run the command. This will create a new package.json file for your project.</p><pre>npm init -y</pre><p><strong>Step 3: </strong>Run the following command to install Cypress as a dev dependency for your project. In this example, I’m using the Cypress version 12.9.0 .</p><pre>npm install cypress --save-dev</pre><p><strong>Step 4: </strong>Run the following command to install dependencies for generating HTML reports using Allure at the end of our test.</p><pre>npm install @shelex/cypress-allure-plugin allure-commandline --save-dev</pre><h3>Setup Test Config and Test Report</h3><p>After the initial setup described above, you’ll need to perform the following changes on your config files to enable Allure as your test reporter.</p><p><strong>Step 1: </strong>Create a new file within your project&#39;s main directory cypress.config.js and add the following code:</p><pre>const { defineConfig } = require(&quot;cypress&quot;);<br>const allureWriter = require(&#39;@shelex/cypress-allure-plugin/writer&#39;);<br><br>module.exports = defineConfig({<br>  e2e: {<br>    setupNodeEvents(on, config) {<br>        allureWriter(on, config);<br>        return config;<br>    }<br>  },<br>  <br>  screenshotsFolder: &#39;cypress/reports/screenshots&#39;,<br>  videosFolder: &#39;cypress/reports/videos&#39;<br>});</pre><p><strong>Step 2: </strong>Create a new file in the following directory cypress/support/e2e.js and add the following code:</p><pre>import &#39;@shelex/cypress-allure-plugin&#39;;</pre><p><strong>Step 3: </strong>Update your package.json file scripts as follows:</p><pre>&quot;scripts&quot;: {<br>  &quot;test&quot;: &quot;npx cypress run --env allure=true,allureResultsPath=cypress/reports/allure-result&quot;,<br>  &quot;generate-report&quot;: &quot;npx allure generate cypress/reports/allure-result --clean -o cypress/reports/allure-report &amp;&amp; allure open cypress/reports/allure-report&quot;<br>},</pre><h3>Writing Your First Test</h3><p>Once you have Cypress installed and configurations implemented, you can create your first test. Create a new file called login.cy.js in the cypress/e2edirectory and add the following code:</p><pre>describe(&#39;Login Page&#39;, () =&gt; {<br>  it(&#39;Logs in with valid credentials&#39;, () =&gt; {<br>    cy.visit(&#39;https://www.saucedemo.com/&#39;)<br>    cy.get(&#39;#user-name&#39;).type(&#39;standard_user&#39;)<br>    cy.get(&#39;#password&#39;).type(&#39;secret_sauce&#39;)<br>    cy.get(&#39;#login-button&#39;).click()<br>    cy.url().should(&#39;include&#39;, &#39;/inventory&#39;)<br>    cy.contains(&#39;Products&#39;).should(&#39;be.visible&#39;)<br>  });<br><br>  it(&#39;Shows an error with invalid credentials&#39;, () =&gt; {<br>    cy.visit(&#39;https://www.saucedemo.com/&#39;)<br>    cy.get(&#39;#user-name&#39;).type(&#39;standard_user&#39;)<br>    cy.get(&#39;#password&#39;).type(&#39;invalidPassword&#39;)<br>    cy.get(&#39;#login-button&#39;).click()<br>    cy.contains(&#39;Username and password do not match any user in this service&#39;).should(&#39;be.visible&#39;)<br>  });<br>});</pre><p>In this example, credentials are entered after visiting the login page, the login button is clicked, and then a check is done to see if the right page or error message is displayed. The first test confirms that the user may log in using valid credentials, and the second test confirms that an error message is presented if invalid credentials are entered.</p><p>We use the cy.visit command to navigate to the login page, and the cy.get command to select and interact with the login form fields. We use the cy.contains command to verify that the correct text is displayed on the page, and the cy.url().should(&#39;include&#39;, ...) command to verify that the URL of the page contains the expected text.</p><h3>Running Your Test (through CLI)</h3><p>Proceed with the following steps after specifying the scripts in your package.json file.</p><p><strong>Step 1: </strong>Run the following command to execute your test. Once the test execution is done, you’ll be able to see the test result summary on your terminal. A new folder called reports will be created, containing the test results in JSON format.</p><pre>npm test</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7FuhhBZ6mX0YmLe1BePWIA.png" /></figure><p><strong>Step 2: </strong>To generate and open an HTML report based on the JSON test result file, run the following command:</p><pre>npm run generate-report</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dzavEmOvKFDScHmxZrVcGQ.png" /></figure><h3><strong>Running Your Test (through Cypress Test Runner)</strong></h3><p>Besides executing through the CLI, you can also run your tests through Cypress Test Runner with the following steps:</p><p><strong>Step 1: </strong>Open the Cypress test runner by running the command ./node_modules/.bin/cypress open on a Mac, or npx cypress open on Windows machine. This will launch the Cypress test runner and allow you to create and run tests for your web app.</p><p><strong>Step 2: </strong>Proceed with the E2E testing configuration and then select a browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aapxd-_Ce4FO50GqMvylRg.png" /></figure><p><strong>Step 3: </strong>Click on your E2E test file to start running the execution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s-jV0TDHQ16WsNeX22-Nqw.png" /></figure><p><strong>Step 4: </strong>Once the test is done, you’ll be able to see the results of your tests as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m7_5Pue5t6tg0it-DVAE0w.png" /></figure><h3>Conclusion</h3><p>By simulating user interactions and confirming expected results, end-to-end testing with Cypress is a powerful approach to making sure that your web app is operating as intended. Using Cypress, you can quickly write and run tests for your web application while configuring them to work in various environments and browsers. I hope that this article has helped you get started with Cypress and will allow you to keep discovering all of this robust testing tool’s features and capabilities.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f3890285578" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with k6: A Beginner’s Guide to Load Testing]]></title>
            <link>https://anivaz.medium.com/getting-started-with-k6-a-beginners-guide-to-load-testing-1249c64118b6?source=rss-beb8620860f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/1249c64118b6</guid>
            <category><![CDATA[html]]></category>
            <category><![CDATA[k6]]></category>
            <category><![CDATA[load-testing]]></category>
            <category><![CDATA[performance-testing]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Wavda Aniva]]></dc:creator>
            <pubDate>Sat, 01 Apr 2023 00:01:45 GMT</pubDate>
            <atom:updated>2023-04-01T00:01:45.152Z</atom:updated>
            <content:encoded><![CDATA[<p>Load testing is an important step in ensuring that an application can handle the expected amount of traffic and user load. k6 is a popular open-source tool that provides extensive functionality for testing web applications, APIs, and microservices sources and is very easy to use. This post will provide an introduction to load testing with k6.</p><h3>Step 1: Installation</h3><p>The first step is to install k6 locally on your machine. k6 has packages for Linux, Mac, and Windows. Alternatively, you can use a Docker container or a standalone binary.</p><p>To install k6, refer to the following instructions: <a href="https://k6.io/docs/get-started/installation/">https://k6.io/docs/get-started/installation/</a>. You can use a package installer or unzip the downloaded binary file and add the k6 executable to your PATH.</p><h3>Step 2: Writing a Simple Load Test Script</h3><p>Once k6 is installed, we can start creating our first load test script which will be written in JavaScript. Within the script, we’re using the http module to send the requests to multiple APIs from <a href="https://reqres.in/">https://reqres.in</a> and we’ll name the file as script.js</p><pre>import http from &#39;k6/http&#39;;<br>import { check, sleep } from &#39;k6&#39;;<br>import { htmlReport } from &quot;https://raw.githubusercontent.com/benc-uk/k6-reporter/main/dist/bundle.js&quot;;<br>import { textSummary } from &quot;https://jslib.k6.io/k6-summary/0.0.1/index.js&quot;;<br><br>export let options = {<br>  stages: [<br>    { duration: &#39;1m&#39;, target: 5 }, // simulate ramp-up of traffic from 0 to 5 users over 1 minute<br>    { duration: &#39;1m30s&#39;, target: 10}, // stay at 10 users for 1minutes 30 seconds<br>    { duration: &#39;1m&#39;, target: 0 }, // ramp-down to 0 users over 1 minute<br>  ],<br>  thresholds: {<br>    http_req_duration: [&#39;p(99)&lt;500&#39;], // 99% of requests must complete within 500ms<br>    http_req_failed: [&#39;rate&lt;0.01&#39;] // request failure rate must be below 1%<br>  },<br>};<br><br>export default function () {<br>  const get_request = {<br>    method: &#39;GET&#39;,<br>    url: &#39;https://reqres.in/api/users?page=2&#39;,<br>  };<br><br>  const post_request = {<br>    method: &#39;POST&#39;,<br>    url: &#39;https://reqres.in/api/users&#39;,<br>    body: {<br>      name: &#39;Wavda&#39;,<br>      job: &#39;QA&#39;,<br>    },<br>    params: {<br>      headers: { &#39;Content-Type&#39;: &#39;application/x-www-form-urlencoded&#39; },<br>    },<br>  };<br><br>  const put_request = {<br>    method: &#39;PUT&#39;,<br>    url: &#39;https://reqres.in/api/users/2&#39;,<br>    body: {<br>      name: &#39;Aniva&#39;,<br>      job: &#39;Engineer&#39;,<br>    },<br>    params: {<br>      headers: { &#39;Content-Type&#39;: &#39;application/x-www-form-urlencoded&#39; },<br>    },<br>  };<br><br>  const delete_request = {<br>    method: &#39;DELETE&#39;,<br>    url: &#39;https://reqres.in/api/users/2&#39;<br>  };<br><br>  const responses = http.batch([get_request, post_request, put_request, delete_request]);<br>  check(responses[0], {<br>    &#39;GET status is 200&#39;: (r) =&gt; r.status === 200,<br>  });<br><br>  check(responses[1], {<br>    &#39;POST status is 201&#39;: (r) =&gt; r.status === 201,<br>  });<br><br>  check(responses[2], {<br>    &#39;PUT status is 200&#39;: (r) =&gt; r.status === 200,<br>  });<br><br>  check(responses[3], {<br>    &#39;DELETE status is 204&#39;: (r) =&gt; r.status === 204,<br>  });<br>}<br><br>export function handleSummary(data) {<br>  return {<br>    &quot;summary.json&quot;: JSON.stringify(data),<br>    &quot;result.html&quot;: htmlReport(data),<br>    stdout: textSummary(data, { indent: &quot; &quot;, enableColors: true })<br>  };<br>}</pre><p>From the load test script above, we’ve implemented:</p><h4>Requests</h4><ul><li>GET <a href="https://reqres.in/api/users?page=2">https://reqres.in/api/users?page=2</a></li><li>POST <a href="https://reqres.in/api/users">https://reqres.in/api/users</a></li><li>PUT <a href="https://reqres.in/api/users/2">https://reqres.in/api/users/2</a></li><li>DELETE <a href="https://reqres.in/api/users/2">https://reqres.in/api/users/2</a></li></ul><h4>Traffic Stages</h4><ol><li>For 1 minute, we’ll simulate the ramp-up of traffic from 0 to 5 users</li><li>Stay at 10 users for 1 minute and 30 seconds</li><li>At the end of the test, we’ll ramp down to 0 users over 1 minute</li></ol><h4>Test Scenarios and Checks</h4><ul><li>99% of requests’ response time must complete within 500ms</li><li>request failure rate must be below 1%</li><li>response status code for each request is correct by checking it using a check function</li></ul><h4>Test Report</h4><ul><li>a handleSummary function was also added which will generate a test report in a form of JSON and HTML files.</li></ul><h3>Step 3: Run the Load Test</h3><p>Now that we have a load test script called script.js, we can run the load test using k6 with the following steps:</p><ol><li>Open a terminal or command prompt and navigate to the folder containing the test script.</li><li>Run the following command and specify the script file name.</li></ol><pre>k6 run script.js</pre><p>Once the tests are completed, you will be able to see the test results, including the number of requests, response time, and error rate within the terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FQpLXUMlJnBQN3Xq68NyGw.png" /><figcaption>Execution Result</figcaption></figure><p>and also in an HTML file called <strong>result.html</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OfwI4fgpgPwhTPX7w32nqQ.png" /><figcaption>Request Metrics</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PFmNCRDRi_HeFZGwcgpXsQ.png" /><figcaption>Other Stats</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CmFryYv9B4oo6jcbK5F-vw.png" /><figcaption>Checks &amp; Groups</figcaption></figure><h3>Step 4: Analyzing Load Test Results</h3><p>k6 includes several integrations for visually analyzing load test results. Two popular integrations are Grafana and InfluxDB. Grafana enables the creation of interactive dashboards that visualize load test data. InfluxDB is a time-series database capable of storing and analyzing load test data.</p><h3>Conclusion</h3><p>Load testing with k6 is a powerful and easy-to-use way to ensure that your application can handle the expected traffic and user load. By following these steps, you should have a good understanding of how to write load test scripts, run load tests, and analyze load test results with k6.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1249c64118b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WebdriverIO and Page Object Model: Designing Scalable Test Suites]]></title>
            <link>https://anivaz.medium.com/webdriverio-and-page-object-model-designing-scalable-test-suites-344d8e55c24b?source=rss-beb8620860f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/344d8e55c24b</guid>
            <category><![CDATA[webdriverio]]></category>
            <category><![CDATA[mocha]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[allure]]></category>
            <category><![CDATA[page-object-model]]></category>
            <dc:creator><![CDATA[Wavda Aniva]]></dc:creator>
            <pubDate>Fri, 17 Mar 2023 11:41:29 GMT</pubDate>
            <atom:updated>2023-03-17T11:41:29.312Z</atom:updated>
            <content:encoded><![CDATA[<p>Automated testing is an essential component of modern software development, as it allows us to identify and fix issues quickly and efficiently. However, as applications grow in size and complexity, maintaining and scaling automated tests becomes increasingly challenging. This is where WebdriverIO and the Page Object Model (POM) come in.</p><h3>What is WebdriverIO?</h3><p>WebdriverIO is a popular framework for automating JavaScript tests. It supports both synchronous and asynchronous test execution thanks to its simple syntax. This means we can write tests that handle operations like waiting for elements to load without resorting to complex control flow logic. WebdriverIO is based on the WebDriver protocol, which provides a standardized method of controlling web browsers.</p><h3>What is Page Object Model?</h3><p>Page Object Model (POM) is a design pattern used in automation testing to separate code that interacts with the UI of an application from the test logic. POM makes tests more maintainable and easier to scale by allowing changes to the UI without affecting the tests. To use POM, we create classes called Page Objects that encapsulate UI interaction code for each page or component of an application. POM allows tests to interact with the UI without needing to know the details of how that interaction is implemented.</p><p>This article will show you how to use POM in WebdriverIO to create more efficient and robust automated test suites. So, let’s get started on how to build scalable test suites with WebdriverIO and POM!</p><h3>Pre-requisites</h3><ol><li><a href="https://nodejs.org/en/download/">Node.js</a> (version 12 or later)</li><li>npm (version 6 or later)</li><li>Source code editor e.g. <a href="https://code.visualstudio.com/download">Visual Studio Code</a></li></ol><h3>Initial Project Setup</h3><h4>Step 1: Create a new Node.js project</h4><p>We’ll start by creating a new project and naming the project folder <strong>wdio-demo</strong>. Using the terminal or command line, run the following command. It will generate the default configurations needed for the tests.</p><pre>npm init -y</pre><h4>Step 2: Install WebdriverIO and its dependencies</h4><p>Next, we need to install WebdriverIO and its dependencies. Run the following command in your terminal which will install WebdriverIO and its CLI tool as dev dependencies in your project:</p><pre>npm install webdriverio @wdio/cli --save-dev</pre><h4>Step 3: Generate a configuration file</h4><p>WebdriverIO uses a configuration file to set up your testing environment. We can generate a default configuration file using the CLI tool we installed in the previous step. Run the following command in your terminal:</p><pre>npx wdio config -y</pre><p>This will launch a wizard to guide you through generating a configuration file. Answer the questions according to your testing needs, and a wdio.conf.js file will be generated in your project root directory.</p><p>Once all the steps above are done, your test project folder will look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3dWZnVNvyJJV5SxRjwqvlA.png" /></figure><h4>Step 4: Install dependencies and configure the test report</h4><p>Next, we need to install the dependencies that will allow us to generate an HTML report for the test execution. In this example, we will use Allure for the test report. Run the following command in your terminal which will install @wdio/allure-reporter and allure-commandline as dev dependencies in your project:</p><pre>npm install webdriverio @wdio/allure-reporter allure-commandline --save-dev</pre><p>Once the dependencies installation is done, you can modify your wdio.conf.js file by adding the following configuration to enable the generation of test reports through Allure and the capture of a screenshot at the completion of each test.</p><pre>exports.config = {<br><br><br>  reporters: [&#39;spec&#39;, [&#39;allure&#39;, {<br>      outputDir: &#39;./allure-results&#39;,<br>      disableWebdriverStepsReporting: true,<br>      disableWebdriverScreenshotsReporting: false,<br>  }]],<br><br>  afterTest: async function (test, context, { error, result, duration, passed, retries }) {<br>      await browser.takeScreenshot();<br>  },<br><br><br>}</pre><p>Lastly, within your package.json file, add the following config which will allow you to use npm test command to execute all the tests, and npm run report command to generate the Allure HTML reports.</p><pre>&quot;scripts&quot;: {<br>  &quot;test&quot;: &quot;npx wdio wdio.conf.js&quot;,<br>  &quot;report&quot;: &quot;npx allure generate allure-results --clean &amp;&amp; npx allure open&quot;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cMbfOxbN9jZEbrZjbvQgoQ.png" /></figure><h3>Creating Tests</h3><h4>Step 1: Write your page objects</h4><p>In this section, using a sample application <a href="https://opensource-demo.orangehrmlive.com/">https://opensource-demo.orangehrmlive.com/</a>, we will use WebdriverIO to interact with the application’s UI and create a Page Object for each page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dt8mnQ3xtr1QhqDt6SjbWQ.png" /></figure><p>We will start with a main page object which contains all methods, selectors, and functionality shared across all page objects. In this example, we will name the file as page.js</p><pre>module.exports = class Page {<br>    open (path) {<br>        browser.maximizeWindow();<br>        return browser.url(https://medium.com/%60https://opensource-demo.orangehrmlive.com/$%7Bpath%7D%60)<br>    }<br>}</pre><p>Here’s an example of what our Page Object for the login page might look like which contains specific selectors and methods that exist on the Login Page. In this login.page.js file:</p><ul><li>Selectors are defined using getter methods.</li><li>We’ve also added a method to encapsulate automation code to interact with the page e.g. async login to log in using a username and password.</li><li>The page extends a main page object and allows overwriting specific options from the main page object to adapt it to the Login Page object for example with the function open .</li></ul><pre>const Page = require(&#39;./page&#39;);<br><br>class LoginPage extends Page {<br>    get inputUsername () {<br>        return $(&#39;//input[@name=&quot;username&quot;]&#39;);<br>    }<br><br>    get inputPassword () {<br>        return $(&#39;//input[@name=&quot;password&quot;]&#39;);<br>    }<br><br>    get btnLogin () {<br>        return $(&#39;//button[contains(.,&quot;Login&quot;)]&#39;);<br>    }<br><br>    get errorMessageInvalidCredentials() {<br>        return $(&#39;//*[text()=&quot;Invalid credentials&quot;]&#39;);<br>    }<br><br>    async login (username, password) {<br>        await this.inputUsername.setValue(username);<br>        await this.inputPassword.setValue(password);<br>        await this.btnLogin.click();<br>    }<br><br>    open () {<br>        return super.open(&#39;web/index.php/auth/login&#39;);<br>    }<br>}<br><br>module.exports = new LoginPage();</pre><p>We will also create a new page object to store the locator of the user area’s header that only logged-in users can access called header.page.js .</p><pre>const Page = require(&#39;../page&#39;);<br><br>class Header extends Page {<br>    get headerUserArea () {<br>        return $(&#39;//*[@class=&quot;oxd-topbar-header-userarea&quot;]&#39;);<br>    };<br>};<br><br>module.exports = new Header();</pre><h4>Step 2: Write your first test</h4><p>Once we’ve created our Page Objects, we can use them to write maintainable and scalable tests. For example, we will write a login test using the Page Object for the login page for the following scenarios:</p><ul><li>make sure users can log in when they enter valid credentials</li><li>make sure users get a correct error message when invalid credentials entered</li></ul><p>Here’s an example of what that tests might look like:</p><pre>const LoginPage = require(&#39;../pageobjects/login.page&#39;)<br>const Header = require(&#39;../pageobjects/client/header.page&#39;)<br><br>describe(&#39;Login Page&#39;, () =&gt; {<br>    beforeEach(async() =&gt; {<br>        await LoginPage.open();<br>    });<br><br>    it(&#39;allows users to log in with valid credentials&#39;, async () =&gt; {<br>        await LoginPage.login(&#39;Admin&#39;, &#39;admin123&#39;);<br>        await expect(Header.headerUserArea).toBeExisting();<br>    });<br><br>    it(&#39;displays an error message for invalid credentials&#39;, async () =&gt; {<br>        await LoginPage.login(&#39;Admin&#39;, &#39;123&#39;);<br>        await expect(LoginPage.errorMessageInvalidCredentials).toBeExisting();<br>    });<br>});</pre><h4>Step 3: Run the test</h4><p>Finally, let’s run the test we just wrote. Run the following command in your terminal:</p><pre>npm test</pre><p>Once all the tests are executed, the output will look something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WT5CCcklNHqZh-5hOVgqig.png" /></figure><h4>Step 4: Generate the test report</h4><p>Run the following command in your terminal:</p><pre>npm run report</pre><p>This will create a new folder called allure-report which will store and open the newly generated HTML report.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*umiybnH2q4V7A_-6dWOlpA.png" /></figure><p>Congratulations! You’ve successfully set up WebdriverIO and written your first automated test.</p><p>In conclusion, WebdriverIO and POM are powerful tools that can help us create maintainable and scalable automated tests. By following best practices and designing tests using POM, we can ensure our automated tests remain effective and efficient as applications grow in size and complexity. In this article, we’ve also walked through the process of setting up WebdriverIO from scratch and writing your first test. I hope this guide has been helpful in getting you started with WebdriverIO. Happy testing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=344d8e55c24b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Newman: An Introduction to API Testing Automation]]></title>
            <link>https://anivaz.medium.com/getting-started-with-newman-an-introduction-to-api-testing-automation-959651445cf9?source=rss-beb8620860f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/959651445cf9</guid>
            <category><![CDATA[allure]]></category>
            <category><![CDATA[api-testing]]></category>
            <category><![CDATA[newman]]></category>
            <category><![CDATA[postman]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Wavda Aniva]]></dc:creator>
            <pubDate>Mon, 13 Mar 2023 00:02:50 GMT</pubDate>
            <atom:updated>2023-03-17T03:33:39.009Z</atom:updated>
            <content:encoded><![CDATA[<p>As APIs become more complex and critical to software development, the need for efficient and thorough API testing has never been greater. API testing automation can streamline your testing process, improve test coverage, and ultimately increase software quality.</p><p>Newman, a command-line tool built on Postman, provides a powerful solution for API testing automation. In this article, I’ll introduce you to Newman and demonstrate to you how to use it to get started with API testing automation. This article will provide you with the basic knowledge to use Newman effectively, whether you’re new to API testing or looking for ways to improve your testing workflow.</p><p>There are 2 ways of using Newman after setting up a Postman collection which I will discuss in this article:</p><ol><li>Newman CLI</li><li>Newman as a library</li></ol><p>Here is a step-by-step guide on how to use Newman for API testing.</p><h3>Pre-requisites</h3><ol><li>Postman installed: <a href="https://www.postman.com/downloads/">https://www.postman.com/downloads/</a></li><li>Node.js installed: <a href="https://nodejs.org/en/download/">https://nodejs.org/en/download/</a></li></ol><h3>Setup Postman Collection</h3><h4>Step 1: Create a Postman Collection</h4><p>A Postman Collection is a group of requests that you can organize into folders and run together.</p><ol><li>To create a Collection, open Postman and click the “New” button.</li><li>Select “Collection” and give it a name.</li><li>You can then start adding requests to the collection by clicking the “New” button again and selecting “HTTP Request”.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I7pjLMix1jBUP_YtE2z_xQ.png" /></figure><h4>Step 2: Write Test Scripts</h4><p>In Postman, you can write test scripts to verify that your API responses are correct. Select a request in your collection to write a test script and click on the “Tests” tab. Here, you can write JavaScript code that tests the response from the server. For example, you can assert whether the response status code is 200 or a specific value is returned in the response body.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zolv8HoNzCyZ_vZw4iQEEQ.png" /></figure><h4>Step 3: Export Collection</h4><p>Once you have created your Postman Collection and written your test scripts, export it in JSON format. To do this, click on the three dots next to your collection name and select “Export”. Choose the “Collection v2.1” format and save the file to your local machine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EIUmTzWJHiD_WHHy-rqMJA.png" /></figure><p>In this example, I’ll save the file as <strong>reqres-collection.json</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*1ITNCwo1e8fvPnHJ6S04eQ.png" /></figure><h3>Option 1: Newman CLI</h3><p>Newman is a command-line interface for running Postman collections. It is a powerful tool that allows you to automate your API testing and integrate it into your continuous integration and deployment pipelines. Here is a step-by-step guide on how to use Newman CLI.</p><h4>Step 1: Install Dependencies</h4><p>To use Newman, you first need to install it on your machine. You can install it using npm, which is the Node.js package manager. Open your terminal and run the following command. In this example, besides installing the Newman itself, I will also install <strong>newman-reporter-htmlextra </strong>which will generate an HTML report once the test executions are done.</p><pre>npm install -g newman newman-reporter-htmlextra</pre><p>This will install Newman globally on your machine.</p><h4>Step 2: Run Newman</h4><p>Now that you have your Postman Collection exported as a JSON file, you can use Newman to run your tests. Open your terminal and navigate to the directory where your JSON file is saved. Then, run the following command:</p><pre>newman run collections\reqres-collection.json -r htmlextra</pre><p>This will run all the requests in your collection and execute the test scripts you wrote. A new folder called <strong>newman </strong>will be created, consisting of the HTML report generated from the test execution using <strong>htmlextra</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8WCU7gtT1x93aeaAISvNAw.png" /></figure><p>You can also run your collection for a specific environment or even get the collection and environment from Postman directly without having to export it as a JSON file. Further references for custom execution can be found <a href="https://www.npmjs.com/package/newman">here</a>.</p><h3>Option 2: Newman as a library</h3><p>Newman can also be used as a library within your Node.js project. This allows you to programmatically run collections and tests, and to integrate Newman into your automated testing workflows. Here is a step-by-step guide on how to use Newman as a library.</p><h4>Step 1: Create a Project &amp; Install Dependencies</h4><p>To use Newman as a library, you first need to install it as a dependency of your project. In this example, I will create a project folder called <strong>newman-test. </strong>Open your terminal and navigate to your project directory.</p><p>In this example, besides installing the Newman itself, I will also install <strong>allure-commandline</strong> and <strong>newman-reporter-allure</strong> dependencies to generate an HTML report once the test executions are done using <strong>Allure</strong> with the following command:</p><pre>npm install newman allure-commandline newman-reporter-allure --save-dev</pre><h4><strong>Step 2: Write Your Test Script</strong></h4><p>To use Newman as a library, you need to write a Node.js script that will load your Postman Collection and execute it using Newman. Here is an example script which later I will save as a file called <strong>test.js</strong>:</p><pre>const newman = require(&#39;newman&#39;);<br><br>newman.run({<br>    collection: require(&#39;./collections/reqres-collection.json&#39;),<br>    reporters: &#39;allure&#39;<br>}, function (err) {<br> if (err) { throw err; }<br>    console.log(&#39;collection run complete!&#39;);<br>});</pre><h4>Step 3: Configure the Test Script</h4><p>Within the <strong>package.json </strong>file, add the following script which will</p><ol><li>run the <strong>test.js</strong> file</li><li>generates an Allure report from the allure-results directory</li><li>saves it in the allure-report directory</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*R3FNCD9aRtP1gdxSJUtoMg.png" /></figure><h4>Step 4: Run Your Test</h4><p>Run the following command in the command line</p><pre>npm test</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*FVIIsoRAM9isV2YdFoLdaQ.png" /></figure><p>This command will also open an HTML report in your default browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fFMI0FDmbJQP-k7Jcp9AqQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=959651445cf9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Maximizing the Benefits of Mocha Chai for API Testing: From Organizing Tests to Generating Reports]]></title>
            <link>https://anivaz.medium.com/maximizing-the-benefits-of-mocha-chai-for-api-testing-from-organizing-tests-to-generating-reports-611db29b2b00?source=rss-beb8620860f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/611db29b2b00</guid>
            <category><![CDATA[mocha]]></category>
            <category><![CDATA[supertest]]></category>
            <category><![CDATA[chai]]></category>
            <category><![CDATA[api-testing]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Wavda Aniva]]></dc:creator>
            <pubDate>Fri, 10 Mar 2023 10:01:28 GMT</pubDate>
            <atom:updated>2023-03-10T10:01:28.831Z</atom:updated>
            <content:encoded><![CDATA[<h3>Maximizing the Benefits of Mocha and Chai for API Testing: From Organizing Tests to Generating Reports</h3><p>As the world becomes increasingly interconnected, Application Programming Interfaces (APIs) are becoming crucial to software development. APIs allow different applications to communicate with each other, enabling seamless data transfer and integration.</p><p>However, as APIs grow more complex, it becomes essential to ensure that they function as intended. This is where API testing comes in. By testing APIs, developers can identify bugs, security vulnerabilities, and other issues that might affect the performance of their applications.</p><p>One popular tool for testing APIs is Mocha Chai. Mocha is a JavaScript test framework with a simple and intuitive syntax for creating tests. Chai is an assertion library that allows developers to make assertions about the behavior of their APIs.</p><p>Together, Mocha Chai offers a powerful and flexible testing framework for APIs. Developers can use Mocha Chai to test everything from simple RESTful APIs to more complex web services.</p><p>This article will explore how to use Mocha Chai to test APIs. We will cover the basics of writing API tests with Mocha Chai and provide examples of common test scenarios. By the end of this article, you should have a good understanding of how to use Mocha Chai to test your own APIs.</p><h3>Pre-Requisites</h3><ul><li><strong>Node.js</strong> downloaded and installed. Download: <a href="https://nodejs.org/en/download/">link</a></li><li><strong>IDE</strong> such as Visual Studio Code. Download: <a href="https://code.visualstudio.com/">link</a></li></ul><h3>Setup</h3><h4>Step 1: Create a project folder</h4><p>In this example, I’ll create a project folder called <strong><em>mocha-chai-test.</em></strong></p><h4>Step 2: Install dependencies</h4><p>You’ll need to install some dependencies within the project folder to get started. You can do this using npm, the package manager for Node.js. Open a terminal or command prompt and run the following command.</p><pre>npm install mocha chai supertest mochawesome mochawesome-report-generator util --save-dev</pre><p>with:</p><ul><li><strong>mocha </strong>as the test framework</li><li><strong>chai </strong>for assertions</li><li><strong>supertest </strong>as the library for HTTP assertions</li><li><strong>mochawesome </strong>and <strong>mochawesome-report-generator </strong>will be used to generate a test report in the form of an HTML file</li></ul><p>Once installed, the following files will be created in your test folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lROObao4-dpsUJvNFehN-A.png" /></figure><h4>Step 3: Set up a test file</h4><p>Create a new file called <strong>api.test.js</strong> (or any other name you prefer) in your project’s test directory. This is where you’ll write your API tests.</p><h4>Step 4: Write your first test</h4><p>In your api.test.js file, import <strong>Chai, Supertest, addContext, </strong>and<strong> util</strong>.</p><ul><li>As an example, I’ve set the base URL for my APIs as <strong>https://my-base-url.in/api</strong></li><li><strong>addContext</strong> helper method will be used to associate additional information with a test</li><li>Here I’ve also initiated a <strong>response</strong> variable that will store the response of each test before passing it for assertion.</li></ul><pre>const supertest = require(&#39;supertest&#39;)(&#39;https://my-base-url.in/api&#39;);<br>const expect = require(&#39;chai&#39;).expect;<br>const addContext = require(&#39;mochawesome/addContext&#39;);<br>const util = require(&#39;util&#39;);<br>let response;</pre><p>Then, write your first test.</p><pre>describe(&#39;Test Users&#39;, () =&gt; {<br>    it(&#39;should return a 200 response on GET /users&#39;, async() =&gt; {<br>        response = await supertest<br>            .get(&#39;/users&#39;)<br>            .query({&#39;page&#39;: 2})<br>            .then(response =&gt; {<br>                return response;<br>        });<br><br>        expect(response.statusCode).to.be.equal(200);<br>        expect(response.body.page).to.be.equal(2);<br>    });<br>});</pre><p>Examples of other requests would look something like this:</p><ul><li><strong>POST request</strong> with authorization and custom header</li></ul><pre>it(&#39;should create a new user on POST /users&#39;, async() =&gt; {<br>      const name = &quot;morpheus&quot;;<br>      const job = &quot;leader&quot;;<br><br>      response = await supertest<br>          .post(&#39;/users&#39;)<br>          .set(&#39;Authorization&#39;, token-goes-here)<br>          .set(&#39;Content-Type&#39;, &#39;application/x-www-form-urlencoded&#39;)<br>          .send({<br>              name: name,<br>              job: job<br>          })<br>          .then(response =&gt; {<br>              return response;<br>      });<br><br>      expect(response.statusCode).to.be.equal(201);<br>      expect(response.body.name).to.be.equal(name);<br>      expect(response.body.job).to.be.equal(job);<br> });</pre><ul><li><strong>POST request</strong> with file attachment</li></ul><pre>it(&#39;should update user image on POST /users/:user_id/profile&#39;, async() =&gt; {<br>    const filepath = &quot;resources/my-image.jpg&quot;<br>    response = await supertest<br>        .post(endpoint)<br>        .set(&#39;Content-Type&#39;, &#39;multipart/form-data&#39;)<br>        .attach(&#39;image&#39;, filepath, { contentType: &#39;image/jpeg&#39; })<br>        .then(response =&gt; {<br>            return response;<br>        });<br><br>    expect(response.statusCode).to.be.equal(201);<br>});</pre><ul><li><strong>PUT request</strong></li></ul><pre>it(&#39;should update user detail on PUT /users/:user_id&#39;, async() =&gt; {<br>    const new_job = &quot;zion resident&quot;;<br><br>    response = await supertest<br>        .put(&#39;/users/2&#39;)<br>        .send({<br>            job: new_job<br>        })<br>        .then(response =&gt; {<br>            return response;<br>    });<br><br>    expect(response.statusCode).to.be.equal(200);<br>    expect(response.body.job).to.be.equal(new_job);<br>});</pre><ul><li><strong>DELETE request</strong></li></ul><pre>it(&#39;should delete user on DELETE /users/:user_id&#39;, async() =&gt; {<br>    response = await supertest<br>        .delete(&#39;/users/2&#39;)<br>        .then(response =&gt; {<br>            return response;<br>    });<br><br>    expect(response.statusCode).to.be.equal(204);<br>});</pre><ul><li><strong>Before/After</strong> <strong>Tests: </strong>You can also add other steps that you might want to execute using BeforeEach or AfterEach tests. This example will allow you to log the response body of the API under test to the mochawesome HTML report.</li></ul><pre>afterEach(function() {<br>    addContext(this, {<br>        title: &#39;Response Body&#39;,<br>        value: util.inspect(response.body)<br>    });<br>});</pre><h4>Step 5: Run your tests</h4><p>Add the following config within your <strong>package.json</strong> file</p><pre>&quot;scripts&quot;: {<br>  &quot;test&quot;: &quot;mocha &#39;**/*.test.js&#39; --reporter mochawesome --require mochawesome/register&quot;<br>},</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*VKjPcQ0l_SDs0uEPsCYFAg.png" /></figure><p>Execute the following command on a terminal or command prompt</p><pre>npm test</pre><p>This will allow you to run your <strong>test.js</strong> files, output the results in the terminal, and generate an HTML report using mochawesome.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UXGZd0c9HkVhKEhMcLC6lw.png" /></figure><p>Congratulations, you’ve successfully set up API testing using Mocha Chai! From here, you can write more tests to cover different scenarios and ensure the robustness of your API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uuCvj8aDKGNNO-Z-iBuFOQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=611db29b2b00" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>