<?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 Sudheer on Medium]]></title>
        <description><![CDATA[Stories by Sudheer on Medium]]></description>
        <link>https://medium.com/@sudheer-baraker?source=rss-f17fb69241fb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*E5f6veVEmP7lgP12</url>
            <title>Stories by Sudheer on Medium</title>
            <link>https://medium.com/@sudheer-baraker?source=rss-f17fb69241fb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 00:44:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sudheer-baraker/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[Cypress Automation Interview Questions & Answers]]></title>
            <link>https://sudheer-baraker.medium.com/cypress-automation-interview-questions-answers-94f4af7d3752?source=rss-f17fb69241fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/94f4af7d3752</guid>
            <dc:creator><![CDATA[Sudheer]]></dc:creator>
            <pubDate>Fri, 25 Jul 2025 18:27:04 GMT</pubDate>
            <atom:updated>2025-07-25T18:27:04.044Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. What is Cypress?</h3><p>Cypress is a modern end-to-end testing framework designed specifically for web applications. Unlike traditional testing tools, Cypress operates directly in the browser, providing real-time testing capabilities and an intuitive debugging experience. It allows developers to write tests using JavaScript, enabling seamless integration with existing workflows, and facilitates rapid development with features like automatic waiting and time travel debugging.</p><h3>2. What are the advantages of Cypress?</h3><p>Here are some of the benefits of using Cypress:</p><ul><li><strong>Real-Time Reloads</strong>: Cypress automatically reloads tests in real-time as you make changes, speeding up the development and testing process.</li><li><strong>Faster: </strong>Cypress executes commands directly on the browser, making it faster than <a href="https://www.softwaretestingmaterial.com/selenium-tutorial/">Selenium</a>. It also runs tests in parallel and automatically retries failed ones, saving time and effort in testing and issue identification.</li><li><strong>Time Travel Debugging</strong>: Cypress allows “time travel” to inspect application states during test execution, making issue diagnosis quicker. It takes snapshots of each test step automatically, with no configuration needed.</li><li><strong>Debugging: </strong>The Cypress Debuggability feature offers access to developer tools within the browser, allowing for direct debugging in the browser environment.</li><li><strong>Automatic Waiting</strong>: Cypress automatically waits for commands and assertions or any animation to complete before proceeding, eliminating the need for manual waits or timeouts.</li><li><strong>Easy Setup</strong>: With straightforward installation and configuration, getting Cypress up and running is quick and hassle-free.</li><li><strong>Video capture: </strong>Cypress enables video capture, allowing you to record the entire test execution process.</li><li><strong>Rich Assertions</strong>: Cypress provides an extensive range of built-in assertions, making it easier to validate application behavior.</li><li><strong>Network Traffic Control</strong>: The framework allows for easy manipulation of requests and responses, enabling thorough testing of edge cases and error handling.</li><li><strong>Cross-Origin Testing</strong>: Cypress supports testing across multiple origins, making it versatile for applications with complex architectures.</li><li><strong>Comprehensive Documentation</strong>: Well-written and detailed documentation is readily available, aiding developers in understanding and effectively using Cypress.</li><li><strong>API Testing</strong>: Cypress provides robust capabilities for API testing. Users can easily send HTTP requests using the `cy.request()` method to validate responses, check status codes, and inspect the data returned from APIs. The ability to intercept and manipulate API requests also facilitates testing various scenarios, including error responses and rate limiting, making it a comprehensive solution for modern web application testing.</li><li><strong>Open Source</strong>: Being an open-source tool, Cypress provides a robust community and the advantage of continuous updates and enhancements from contributors.</li></ul><h3>3. What are the disadvantages of using Cypress?</h3><p>Here are some of the disadvantages of using Cypress:</p><ul><li><strong>Limited Browser Support</strong>: Currently, Cypress primarily supports Chrome and Electron, with limited support for Firefox and no support for Internet Explorer, which can restrict testing on some platforms.</li><li><strong>No Native Mobile Testing</strong>: Cypress doesn’t natively support mobile application testing, requiring additional frameworks or workarounds to achieve this.</li><li><strong>Single Origin Policy</strong>: Complex applications that require cross-origin testing can face challenges, as Cypress is designed with a single-origin policy in mind.</li><li><strong>Steep Learning Curve for Advanced Features</strong>: While general usage is straightforward, mastering advanced features may require more time and effort.</li><li><strong>Serial Execution</strong>: Tests are executed serially rather than in parallel, which could slow down larger test suites compared to other frameworks that support parallel execution.</li></ul><h3>4. How to Install and Setup Cypress</h3><p>Installing and setting up Cypress is straightforward and can be done in a few steps. First, ensure you have Node.js installed on your system, as Cypress is built on top of it. You can download Node.js from <a href="https://nodejs.org/">the official site</a>.</p><p><strong>Initialize your project</strong>: Open your terminal and navigate to your project directory. Use the following command to create a new ‘package.json’ file if you don’t have one already.</p><pre>npm init -y</pre><p><strong>Install Cypress</strong>: You can install Cypress as a development dependency using npm with the following command:</p><pre>npm install cypress --save-dev</pre><p><strong>Open Cypress</strong>: Once installed, you can open the Cypress application by running:</p><pre>npx cypress open</pre><p>This command will create a ‘cypress’ folder in your project structure, containing example tests and essential folders for your test code.</p><p><strong>Configure Cypress</strong>: You can customize your settings by editing the ‘cypress.json’ configuration file that gets generated during the installation. Here you can set base URL, timeouts, and other configurations to better suit your testing needs.</p><p>By following these steps, you will have successfully installed and set up Cypress, ready for you to start writing and running your tests.</p><h3>5. What are the Components of Cypress?</h3><p>Cypress consists of several key components that work together to provide a comprehensive end-to-end testing framework. These components include:</p><ol><li><strong>Cypress Test Runner</strong>: The core of the Cypress framework, it allows users to execute tests directly in the browser. This interactive environment provides real-time feedback, enabling developers to observe test execution and pinpoint failures immediately.</li><li><strong>Cypress Dashboard</strong>: This cloud service provides a visual representation of the testing process, allowing teams to monitor test results, performance metrics, and debugging information. It helps teams maintain visibility over their testing outcomes and insights.</li><li><strong>Cypress CLI</strong>: The Command Line Interface (CLI) enables developers to run tests, configure settings, and automate their testing processes efficiently. The CLI is essential for integrating Cypress into continuous integration (CI) environments.</li><li><strong>Assertion Libraries</strong>: Cypress comes with built-in assertion libraries such as Chai and Sinon that facilitate easy and robust test validations. These libraries allow testers to write clear and expressive tests, ensuring that application behaviour meets expectations.</li><li><strong>Plugins</strong>: Cypress supports a variety of plugins which can extend its functionality. These plugins can enhance features, integrate with various tools, and provide additional utilities that cater to specific testing needs.</li><li><strong>Framework Integrations</strong>: Cypress seamlessly integrates with popular testing frameworks like Mocha and Jasmine, allowing users to choose their preferred style of testing while leveraging Cypress’s powerful features.</li></ol><p>Together, these components create a versatile and powerful environment for testing web applications, facilitating a streamlined development and testing workflow.</p><h3>6. What is a Cypress Test Runner?</h3><p>A Cypress Test Runner is an innovative tool designed for end-to-end testing of web applications. It provides a robust environment that allows developers and testers to write, run, and debug tests with ease. Unlike traditional test runners, Cypress operates directly within the browser, enabling real-time reloading and testing capabilities. This unique architecture allows users to see their tests execute in a live browser, making it easier to diagnose issues and understand the tests’ behaviour.</p><p>The Cypress Test Runner supports both JavaScript and TypeScript, offering developers flexibility in their testing approach, alongside powerful features like automatic waiting, which reduces the need for manual waits or sleeps in tests. Overall, the Cypress Test Runner enhances the testing experience, leading to faster development cycles and more reliable applications.</p><h3>7. What is a Cypress Dashboard?</h3><p>The Cypress Dashboard is a cloud-based service that provides a centralized interface for accessing and managing Cypress test results. It offers valuable insights into test runs by allowing developers and teams to monitor their tests in real-time, view analytics, and track test performance over time. With features such as test result history, retry capabilities, and recording of test video, the Dashboard enhances collaboration among team members by providing a comprehensive overview of testing outcomes. Additionally, it includes detailed logs and screenshots that help in diagnosing failures more efficiently. By integrating with CI/CD pipelines, the Cypress Dashboard streamlines the testing process, enabling teams to ensure higher quality software delivery with ease.</p><h3>8. What is Cypress CLI?</h3><p>Cypress CLI (Command Line Interface) is a powerful tool that allows developers to execute Cypress commands directly from the terminal. It provides a streamlined way to run tests, manage configurations, and interact with the Cypress framework without the need for a graphical user interface. With Cypress CLI, users can initiate test runs, specify browsers, control test environments, and even trigger parallel test execution with simple commands. Additionally, it supports various options for configuration, making it highly versatile for integrating Cypress into continuous integration and delivery (CI/CD) pipelines. By leveraging the Cypress CLI, developers can enhance their testing workflows and automate testing processes more efficiently.</p><h3>9. Explain Cypress Architecture?</h3><p>Cypress operates on a unique architecture compared to traditional testing frameworks. It runs directly in the browser, enabling it to manipulate the DOM and access application code in real-time. This architecture consists of a Node.js server that handles test execution, while the browser displays the application’s UI and executes the tests synchronously. This separation allows for better control over the test environment, provides instant access to application states, and offers real-time reloading, making debugging and test writing more efficient.</p><h3>10. How Cypress Architecture is different from Selenium?</h3><p>Cypress and Selenium are both popular tools for end-to-end testing, but their architectures differ significantly, influencing how tests are executed and their overall performance. Selenium operates by using WebDriver, which sends commands to a browser via a browser-specific driver. This means that tests run in a separate process, which can slow down execution due to the time it takes to communicate between the test script and the browser.</p><p>On the other hand, Cypress executes tests directly in the browser, running in the same context as the application being tested. This allows for faster execution and easier debugging, as developers can interact with the application in real-time and observe various elements’ states without the latency associated with remote commands. Additionally, Cypress automatically waits for commands and assertions, reducing flakiness and making tests more reliable. Overall, Cypress offers a more streamlined and developer-friendly experience compared to Selenium’s more traditional approach.</p><p><strong>Don’t miss: </strong><a href="https://www.softwaretestingmaterial.com/selenium-interview-questions/">Real time Selenium Interview Questions</a></p><h3>11. How do you use Cypress framework with Java or C# like Selenium?</h3><p>Cypress framework cannot be directly used with Java or C#, as it is specifically designed for JavaScript and TypeScript, unlike Selenium which supports multiple programming languages.</p><h3>12. Can you use JUnit or TestNG in Cypress?</h3><p>No, JUnit and TestNG cannot be used with Cypress, as it is specifically built for testing with JavaScript and does not support Java testing frameworks. Cypress comes with testing framework known as Mocha, which is used for structuring tests and providing assertions.</p><h3>13. Write some difference between Cypress and Selenium?</h3><ul><li><strong>Execution Environment</strong>: Cypress operates directly within the browser, executing commands in the same run-loop as the application being tested. In contrast, Selenium interacts with the browser via WebDriver, which introduces latency as commands are sent over the network.</li><li><strong>Programming Language Support</strong>: Cypress is primarily designed for JavaScript and TypeScript, making it ideal for modern web applications built with these technologies. Selenium, on the other hand, supports multiple programming languages, including Java, C#, Python, and Ruby.</li><li><strong>Real-Time Reloading</strong>: Cypress provides real-time reloading out of the box, allowing developers to see changes reflected in tests immediately as they are written. Selenium does not have this feature natively and requires additional configuration for similar functionality.</li><li><strong>Test Flakiness</strong>: Cypress reduces test flakiness by automatically waiting for elements to become visible and ready for action. Selenium often requires manual waits and checks, which can lead to inconsistencies in test execution.</li><li><strong>Network Traffic Control</strong>: Cypress has built-in capabilities for network traffic control, providing a way to stub and intercept requests without extensive configurations. While Selenium can achieve this, it typically requires additional libraries or tools to test network interactions effectively.</li></ul><blockquote>Read in depth differences between <a href="https://www.softwaretestingmaterial.com/cypress-vs-selenium/">Cypress vs Selenium</a> here</blockquote><h3>14. What browsers does Cypress support?</h3><p>Cypress provides robust support for a range of modern browsers, ensuring that developers can test their applications across various environments. As of now, Cypress officially supports the following browsers:</p><ul><li><strong>Chrome</strong>: The most commonly used browser for testing, Cypress provides extensive support for the latest versions of Chrome.</li><li><strong>Chromium</strong>: Similar to Chrome, the Chromium browser is also fully supported for testing purposes.</li><li><strong>Electron</strong>: Cypress includes a built-in version of Electron, which is useful for testing applications that run in this framework.</li><li><strong>Firefox</strong>: Cypress has been expanding its support, and it continues to enhance compatibility with various versions of Firefox.</li><li><strong>Edge</strong>: The Chromium-based version of Microsoft Edge is supported, allowing for testing across different platforms.</li></ul><p>By supporting these browsers, Cypress enables developers to ensure their web applications behave consistently across all major platforms.</p><h3>15. How do you create a basic test case in Cypress?</h3><p>To write a basic test case in Cypress, you can follow these steps:</p><p><strong>Set Up Your Test File</strong>: Create a new test file in the `cypress/integration` folder. For example, you can name it `basic_test.spec.js`.</p><p><strong>Describe Your Test</strong>: Use the `describe` function to group your tests logically. This helps in organizing your test structure.</p><pre>describe(&#39;My First Test&#39;, () =&gt; {<br>       // Test cases will go here<br>   });</pre><p><strong>Define a Test Case</strong>: Inside the `describe` block, use the `it` function to define individual test cases. Here, you can provide a string description of what the test does and a function containing the test logic.</p><pre>it(&#39;should visit the homepage and verify title&#39;, () =&gt; {<br>       // Test logic will go here<br>   });</pre><p><strong>Implement Test Steps</strong>: Use Cypress commands to interact with the application. For instance, to visit a webpage and check the title, you can do the following:</p><pre>cy.visit(&#39;https://example.com&#39;); // Navigate to a URL<br>   cy.title().should(&#39;include&#39;, &#39;Example Domain&#39;); // Verify the title</pre><p><strong>Run Your Test</strong>: Save the file and run your Cypress tests using the Cypress Test Runner, ensuring your test case executes as expected.</p><p>Here’s a complete basic test case example:</p><pre>describe(&#39;My First Test&#39;, () =&gt; {<br>    it(&#39;should visit the homepage and verify title&#39;, () =&gt; {<br>        cy.visit(&#39;https://example.com&#39;);<br>        cy.title().should(&#39;include&#39;, &#39;Example Domain&#39;);<br>    });<br>});</pre><p>This structure serves as a straightforward yet effective method to initiate your testing journey with Cypress.</p><h3>16. What are some common Cypress commands and how are they used?</h3><p>Cypress offers a wide range of commands that facilitate efficient and effective testing. Here are some of the most commonly used commands:</p><p><strong>‘cy.visit(url)’:</strong> This command allows you to navigate to a specified URL. It can be used to load a page before performing any tests.</p><pre>cy.visit(&#39;https://www.softwaretestingmaterial.com&#39;);</pre><p><strong>‘cy.get(selector)’</strong>: Use this command to select DOM elements based on a CSS selector. It’s a fundamental command used frequently to interact with elements.</p><pre>cy.get(&#39;.btn-primary&#39;).click(); // Click a button with class &#39;btn-primary&#39;</pre><p><strong>‘cy.contains(text)’</strong>: This command selects an element that contains the specified text, making it useful for targeting buttons, links, or other elements where the text is known.</p><pre>cy.contains(&#39;Submit&#39;).click(); // Click the &#39;Submit&#39; button</pre><p><strong>‘cy.type(text)’</strong>: This command is used to simulate typing text into an input field.</p><pre>cy.get(&#39;input[name=&quot;email&quot;]&#39;).type(&#39;test@example.com&#39;); // Type email into the input</pre><p><strong>‘cy.should(assertion)’</strong>: This command is used for making assertions about the state of an element.</p><pre>cy.get(&#39;.alert&#39;).should(&#39;be.visible&#39;); // Assert that the alert element is visible</pre><p><strong>‘cy.log()’</strong>: This command is used to display cypress console logs during execution</p><pre>cy.log(‘STM 123’);</pre><p>These commands, among others, allow testers to interact with the application, verify its state, and ensure that it behaves as expected.</p><h3>17. How to check the default configuration in Cypress?</h3><p>The default configuration can be seen Under Cypress window Test Runner &gt; Settings and Configurations.</p><h3>18. How to open the Cypress window and execute tests?</h3><p>To open the Cypress window, navigate to your project directory in the terminal or command prompt and run the command `npx cypress open`. This will launch the Cypress Test Runner, allowing you to view all available tests in your project. Once the window is open, you can select any test file from the list to execute it. The selected test will run in an interactive browser window, displaying real-time results and enabling you to observe the actions as they are performed. If any tests fail, Cypress provides detailed logs and error messages to help you pinpoint issues quickly.</p><h3>19. How to handle new tabs or windows with Cypress?</h3><p>Handling new tabs or windows in Cypress can be a bit tricky since Cypress is designed to run in a single browser tab context. When a link opens a new tab, Cypress does not automatically switch to it; instead, you can modify the link to prevent it from opening in a new tab or use alternative strategies to test the intended functionality. One common approach is to target the URL directly using `cy.visit()`. For example, if you know clicking a link will redirect to another page, you can test that page directly.</p><p>If you need to handle links that open new tabs, consider using an approach like this:</p><pre>cy.visit(&#39;https://sdetunicorns.com&#39;);<br>cy.get(&#39;a[target=&quot;_blank&quot;]&#39;).invoke(&#39;removeAttr&#39;, &#39;target&#39;).click(); // Remove target attribute and click the link<br>cy.url().should(&#39;include&#39;, &#39;/expected-page&#39;); // Check that the new page URL is as expected</pre><p>This code snippet removes the `target` attribute, allowing the link to open in the same tab, making it easier to interact with and test the resulting page.</p><h3>20. What are hooks in Cypress?</h3><p>Hooks in Cypress are functions that allow you to set up conditions that run before or after your tests. They can be particularly useful for performing common tasks such as initializing data or cleaning up after tests. The primary hooks available are `before`, `beforeEach`, `after`, and `afterEach`.</p><ul><li><strong>‘before()’</strong>: This hook runs once before all the tests in a describe block, making it ideal for global setup tasks, such as visiting a URL or seeding the database.</li><li><strong>‘beforeEach()’</strong>: This hook runs before each individual test, allowing for repetitive setup procedures. For instance, you could log in a user before every test that requires authentication.</li><li><strong>‘after()’</strong>: This hook runs once after all tests in a describe block, typically used for cleanup activities like logging out users or resetting application state.</li><li><strong>‘afterEach()’</strong>: Similar to `after`, but runs after each test, allowing you to handle cleanup tasks that need to be performed regardless of whether the test passed or failed.</li></ul><p>Using hooks helps streamline your test code and enhances readability by reducing duplication.</p><h3>21. Which selectors does Cypress support?</h3><p>Cypress supports a variety of selectors for targeting elements within the DOM. The primary selectors include:</p><ul><li><strong>CSS Selectors</strong>: The most commonly used method, which allows you to select elements based on their classes, IDs, attributes, and hierarchy. For example, `cy.get(‘.class-name’)` or `cy.get(‘#id-name’)`.</li><li><strong>Text Selectors</strong>: You can target elements containing specific text using the `cy.contains()` command. For instance, `cy.contains(‘Submit’)` will select an element that has the text “Submit”.</li><li><strong>Attribute Selectors</strong>: Cypress allows selection based on attributes using the syntax: `cy.get(‘[attribute=”value”]’)`.</li><li><strong>Chaining Selectors</strong>: You can chain multiple selectors together to refine your selection, for example, `cy.get(‘.parent-class’).find(‘.child-class’)`.</li></ul><p>These selectors provide flexibility and robustness in identifying and interacting with elements during test automation.</p><h3>22. How to use XPath in Cypress?</h3><p>To effectively use XPath in your Cypress tests, you first need to install the `cypress-xpath` plugin. This can be accomplished by running `npm install -D cypress-xpath` in your project directory. After the installation, you’ll need to include the plugin in your `commands.js` file by adding `require(‘cypress-xpath’)`. Once set up, you can use the `cy.xpath()` command in your test scripts.</p><p>For example, if you want to select an element with a specific XPath, you can write `cy.xpath(‘//button[text()=”Submit”]’)`. This allows for more complex selections that are often easier to express in XPath, especially when dealing with deeply nested structures or when attribute values are subject to change. Remember to validate your XPath expressions using tools like the built-in XPath Tester to ensure they return the correct elements.</p><h3>23. What is the meaning of NPX in Cypress?</h3><p>NPX (Node Package Execute) is a command-line tool that comes with Node.js as a part of its package manager (npm). In the context of Cypress, NPX allows you to execute Cypress commands without needing to install Cypress globally on your system. This is particularly useful for ensuring that you are using the version of Cypress specified in your project’s `package.json` file. When you run `npx cypress open`, NPX temporarily installs Cypress if it’s not already present, retrieves the specified version, and executes the command. This approach helps to keep your project’s dependencies consistent and avoids potential conflicts that may arise from having different global versions of Cypress.</p><h3>24. What’s the difference between npm and npx?</h3><p>NPM (Node Package Manager) and NPX (Node Package Execute) serve distinct but complementary roles within the Node.js ecosystem. NPM is primarily used as a tool for managing packages; it allows developers to install, update, and manage libraries and dependencies in their projects. When you run commands like `npm install &lt;package&gt;`, you are downloading and installing packages into your project, enabling you to use various libraries and frameworks.</p><p>On the other hand, NPX is designed to execute Node packages directly, without the need for installation in the project. It simplifies the process of running command-line tools associated with local packages. For instance, using `npx &lt;command&gt;` allows you to run a binary from a package without permanently installing it, making it convenient for one-off commands or scripts. Ultimately, while NPM focuses on package management, NPX streamlines the execution of those packages, enhancing the overall development workflow.</p><h3>25. What is Cypress’s default timeout value?</h3><p>Cypress’s default timeout value is four seconds. This means that if an assertion or command does not complete within this time frame, it will fail. Users can customize this default timeout setting to suit their testing needs.</p><h3>26. Why add custom timeouts in Cypress?</h3><p>Adding custom timeouts in Cypress is essential to accommodate variations in application performance and network conditions. By adjusting the default timeout values, users can ensure that tests do not fail prematurely due to slow-loading elements or asynchronous operations. This flexibility allows for more reliable test execution, reducing false negatives and providing a smoother testing experience. Custom timeouts also help in managing tests that interact with third-party services, which may exhibit unpredictable response times, ultimately contributing to more robust and accurate end-to-end testing.</p><h3>27. How can you modify the default timeout value in Cypress?</h3><p>To modify the default timeout value in Cypress, users can adjust the setting in the `cypress.json` configuration file. By adding or updating the `”defaultCommandTimeout”` key, users can specify a new timeout value in milliseconds. Additionally, for specific commands, users can pass a `timeout` option directly in the command itself, allowing for more granular control over timeout durations based on testing needs.</p><h3>28. How can you wait for an element to be visible in Cypress?</h3><p>To wait for an element to become visible in Cypress, you can use the `should` assertion along with the `be.visible` condition. This method automatically retries until the element is visible or the timeout expires.</p><pre>cy.get(&#39;.my-element&#39;, { timeout: 10000 }).should(&#39;be.visible&#39;);</pre><h3>29. What are Built-in and Explicit Assertions in Cypress?</h3><p>Built-in assertions in Cypress are automatically included in the testing framework and are executed as part of the command execution process. They ensure that certain conditions are true without the need for the developer to specify them explicitly. For example, when using commands like `should` or `expect`, Cypress can assert the state of an element based on its visibility or content. On the other hand, explicit assertions must be stated directly in the test code by the user, allowing for more tailored checks. These assertions are typically used to validate specific conditions that go beyond the implicit checks, providing greater control over the testing process.</p><h3>30. What is package.json in Cypress?</h3><p>Package.json is a crucial file that defines a Cypress project’s metadata, including its name, version, and description. It also lists the project’s dependencies, specifying the packages required for Cypress to function correctly. Additionally, it contains scripts that can be executed using the command line interface, streamlining tasks such as running tests, starting the Cypress application, or managing configurations. By keeping track of these aspects, package.json ensures that the project is easily maintainable and shareable among different development environments.</p><h3>31. How does Cypress handle browser compatibility testing?</h3><p>Cypress simplifies browser compatibility testing by allowing developers to run tests in multiple browsers seamlessly. It supports popular browsers like Chrome, Firefox, and Edge, enabling users to verify that their applications behave consistently across different environments. Additionally, Cypress provides built-in tools for debugging and inspecting elements, which aids in identifying any compatibility issues that may arise during testing.</p><h3>32. How to run tests in parallel in Cypress?</h3><p>Running tests in parallel can significantly reduce the overall test execution time, especially for large test suites. Cypress provides several ways to enable parallel test execution, primarily through its Dashboard Service. To set up parallel execution, you should first ensure you have the Cypress Dashboard integrated with your project.</p><p><strong>Enable the Dashboard</strong>: Register your project at the <a href="https://dashboard.cypress.io/">Cypress Dashboard</a> and obtain your Project ID.</p><p><strong>Run Tests with the `–parallel` Flag</strong>: Use the command line to run your tests in parallel. The syntax typically looks like this:</p><pre>npx cypress run --record --key &lt;your-record-key&gt; --parallel</pre><p>Make sure to replace `&lt;your-record-key&gt;` with your actual key from the Dashboard.</p><p><strong>Configure Your CI/CD Pipeline</strong>: If you are using a Continuous Integration service (like CircleCI, GitHub Actions, or Travis CI), configure it to execute Cypress in parallel. This often involves enabling parallel runs in your CI settings and ensuring your command includes the necessary flags.</p><p>By following these steps, you can efficiently execute your Cypress tests in parallel, greatly speeding up your testing process while maintaining the reliability of your automated tests.</p><h3>33. How do you handle dynamic elements in Cypress tests?</h3><p>Handling dynamic elements in Cypress tests requires a strategic approach, as these elements may not be immediately available in the DOM when a test runs. To effectively interact with dynamic elements, you can use the `cy.get()` command in combination with strategies like retries and ensuring visibility. Implementing assertions such as `should(‘be.visible’)` helps confirm that the element is present before attempting to interact with it. Additionally, you can use `cy.wait()` for specific requests or use the `cy.intercept()` method to manage and stub network calls, ensuring that the tests only proceed when the necessary data is available. By incorporating these techniques, you can create robust tests that reliably account for dynamic content.</p><h3>34. What is the concept of snapshots in Cypress?</h3><p>Snapshots in Cypress refer to the automatic capturing of the state of the DOM at a specific point during a test execution. This feature allows testers to visualize how elements appear at that moment, facilitating <a href="https://www.softwaretestingmaterial.com/visual-testing/">visual regression testing</a> and ensuring that UI changes do not unintentionally affect the application’s layout or functionality. By leveraging snapshots, developers can easily track changes and identify discrepancies between expected and actual outcomes.</p><h3>35. What are the reporters cypress supports?</h3><p>Cypress supports various reporters that can be used to format test results. By default, it employs the spec reporter for outputting information to the console. Additionally, being built on Mocha, it is compatible with other Mocha reporters such as Junit and Teamcity, enabling users to choose the output format that best suits their needs.</p><h3>36. What is Retry in Cypress, and how can you modify its behavior?</h3><p>Cypress offers a built-in retry mechanism designed to enhance test reliability by automatically re-running failed assertions until they pass or a specified timeout is reached. You can modify this behavior using the `defaultCommandTimeout` configuration option. By adjusting this timeout, you can extend or shorten the duration Cypress waits before retrying a command, thereby accommodating the needs of your tests. For example, setting `defaultCommandTimeout: 10000` will allow each command to retry for up to 10 seconds before failing.</p><pre>cypress run --config defaultCommandTimeout=10000</pre><h3>37. How to Run Tests in Cypress in Headless Mode?</h3><p>Running Cypress tests in headless mode is straightforward and can be accomplished through the command line. Headless mode allows you to execute your tests without a graphical user interface, which is especially useful for continuous integration (CI) pipelines. To run your tests in headless mode, you can use the following command:</p><pre>cypress run</pre><p>This command starts the Cypress test runner in headless mode using the default browser, which is typically Electron. If you want to specify a different browser, such as Chrome or Firefox, you can add the `–browser` flag, like so:</p><pre>cypress run --browser chrome</pre><p>Additionally, you can include various configuration options to tailor the execution to your needs, such as specifying the path to your test files or adjusting the reporter for output format.</p><h3>38. How can you debug in Cypress?</h3><p>Debugging in Cypress can be effectively achieved using the `.debug()` and `.pause()` commands. The `.debug()` command allows you to pause the code execution at a specific point and open the browser’s developer tools to inspect the state of your application. For example:</p><pre>cy.get(&#39;button.submit&#39;).click().debug();</pre><p>Alternatively, you can use the `.pause()` command to halt the test execution until you manually resume it:</p><pre>cy.get(&#39;input[name=&quot;username&quot;]&#39;).type(&#39;myUsername&#39;).pause();</pre><p>Both of these methods provide you with the flexibility to closely examine your application and pinpoint issues during test execution.</p><h3>39. How can I get location Object in Cypress?</h3><p>To retrieve the location object in Cypress, you can use the command `cy.location()`. This command provides access to the current URL, including information such as the pathname, host, hostname, search, hash values etc. For example, invoking `cy.location()` will return the location object for your current test context.</p><h3>40. How can I chain multiple assertions in Cypress?</h3><p>In Cypress, you can chain multiple assertions by using the `should` or `expect` commands consecutively on the same element. This allows you to verify several properties or states of an element in a single test. For instance, you can write `cy.get(‘.active’).should(‘be.visible’).and(‘have.class’, ‘active’).and(‘contain’, ‘Services’)` to check that the element is visible, has the specified class, and contains the correct text. This approach enhances readability and maintainability of your test scripts by grouping related assertions together.</p><h3>Advanced Cypress Interview Questions &amp; Answers For Experienced</h3><h3>41. Can you perform API testing with Cypress? If yes how do you perform API testing using Cypres?</h3><p>Yes, I can perform API testing with Cypress, which is particularly useful for asserting the behavior of our backend APIs alongside your frontend tests. Cypress provides a robust set of commands to interact with APIs, and the `cy.request()` command is a key feature for making HTTP requests. To test an API, you can send GET, POST, PUT, and DELETE requests and evaluate the responses.</p><p>Here’s a simple example of how to perform API testing using Cypress:</p><pre>describe(&#39;API Testing&#39;, () =&gt; {<br>  it(&#39;should retrieve a list of users&#39;, () =&gt; {<br>    cy.request(&#39;GET&#39;, &#39;https://jsonplaceholder.typicode.com/users&#39;)<br>      .then((response) =&gt; {<br>        expect(response.status).to.eq(200);<br>        expect(response.body).to.be.an(&#39;array&#39;);<br>        expect(response.body.length).to.be.greaterThan(0);<br>      });<br>  });<br>  it(&#39;should create a new user&#39;, () =&gt; {<br>    const newUser = {<br>      name: &#39;John Doe&#39;,<br>      email: &#39;john@example.com&#39;<br>    };<br>    cy.request(&#39;POST&#39;, &#39;https://jsonplaceholder.typicode.com/users&#39;, newUser)<br>      .then((response) =&gt; {<br>        expect(response.status).to.eq(201);<br>        expect(response.body).to.have.property(&#39;name&#39;, newUser.name);<br>        expect(response.body).to.have.property(&#39;email&#39;, newUser.email);<br>      });<br>  });<br>});</pre><p>In this example, the first test checks if an API endpoint returns a list of users successfully, while the second test ensures that a new user can be created. By using assertions, we can validate that the API behaves as expected.</p><h3>42. How can I read files in Cypress?</h3><p>In Cypress, reading files is quite straightforward using the `cy.readFile()` command. This function allows you to read the contents of a file from your project’s directory. You can specify the path to the file you want to read, and it returns the contents as a string or JSON, depending on the file type. Here’s a simple example of reading a text file:</p><pre>cy.readFile(&#39;cypress/fixtures/sample.txt&#39;).then((fileContent) =&gt; {<br>// Do something with the fileContent<br>cy.log(fileContent);<br>});</pre><p>For JSON files, you can use the same command, and it will automatically parse the contents into a JavaScript object:</p><pre>cy.readFile(&#39;cypress/fixtures/data.json&#39;).then((data) =&gt; {<br>// Access data from the JSON file<br>cy.log(data.key);<br>});</pre><p>This makes it easy to work with external data or configurations during your test execution.</p><h3>43. How to get the browser properties in Cypress</h3><p>To access browser properties in Cypress, you can use the `Cypress.browser` object. This provides details about the current browser being used for the tests. For example, to log the browser details, you can use:</p><pre>cy.log(Cypress.browser);</pre><p>This will output an object containing properties such as `name`, `version`, and `isHeadless`.</p><h3>44. What are custom commands in Cypress?</h3><p>Custom commands in Cypress enable developers to create reusable functions that encapsulate frequently used actions, thus enhancing the efficiency of tests. By defining these commands in the `commands.js` file, you can streamline your testing scripts and reduce duplication. Here’s a practical example:</p><p><strong>Practical Example:</strong></p><p>Suppose you often need to log into your application for various tests. Instead of writing the login code repeatedly, you can define a custom command like this:</p><pre>// In commands.js<br>Cypress.Commands.add(&#39;login&#39;, (email, password) =&gt; {<br>    cy.visit(&#39;/login&#39;);<br>    cy.get(&#39;input[name=&quot;email&quot;]&#39;).type(email);<br>    cy.get(&#39;input[name=&quot;password&quot;]&#39;).type(password);<br>    cy.get(&#39;button[type=&quot;submit&quot;]&#39;).click();<br>});</pre><p>Now, you can easily use the `login` command in any test case, promoting cleaner and more maintainable code:</p><pre>describe(&#39;User Authentication Tests&#39;, () =&gt; {<br>    it(&#39;should log in a user&#39;, () =&gt; {<br>        cy.login(&#39;user@example.com&#39;, &#39;password123&#39;);<br>        cy.url().should(&#39;include&#39;, &#39;/dashboard&#39;);<br>    });<br>    it(&#39;should log out a user&#39;, () =&gt; {<br>        cy.login(&#39;user@example.com&#39;, &#39;password123&#39;);<br>        cy.get(&#39;button#logout&#39;).click();<br>        cy.url().should(&#39;include&#39;, &#39;/login&#39;);<br>    });<br>});</pre><p>By using custom commands like `cy.login`, you not only ensure consistent behavior across your tests but also simplify the process of making changes if the login procedure evolves over time.</p><h3>45. What’s the difference between cy.readFile() and cy.fixture() functions?</h3><p>The `cy.readFile()` and `cy.fixture()` functions in Cypress, while both used for handling file content, serve different purposes and contexts within testing. The `cy.readFile()` function is more general and allows you to read any file from the file system, which means you can specify the path to any file type and format that exists in your project directory. This flexibility is useful for accessing a variety of files throughout your tests.</p><p>On the other hand, `cy.fixture()` is specifically designed for loading test data and is often used for JSON files stored in the `cypress/fixtures` folder. When you use `cy.fixture()`, Cypress automatically handles loading, parsing, and making the data available in a straightforward manner. Here’s an example of using `cy.fixture()`:</p><pre>cy.fixture(&#39;data.json&#39;).then((data) =&gt; {<br>// Access data from the fixture<br>cy.log(data.key);<br>});</pre><p>In summary, use `cy.readFile()` for more broad file reading needs and `cy.fixture()` when working specifically with fixture files, particularly during test setups that require predefined data.</p><h3>46. How can I write a file in Cypress?</h3><p>To write a file in Cypress, you can use the `cy.writeFile()` command, which is designed to create or overwrite files in your project’s filesystem during test execution. This function is particularly useful for saving test outputs, logs, or dynamically generated data. Here’s a basic example of how to use `cy.writeFile()`:</p><pre>cy.writeFile(&#39;cypress/fixtures/output.json&#39;, {<br>key: &#39;value&#39;,<br>anotherKey: &#39;anotherValue&#39;<br>});</pre><p>In this example, a JSON file named `output.json` is created in the `cypress/fixtures` directory, with the specified key-value pairs. You can also write strings, arrays, or other objects as needed. By utilizing this function, you can ensure your test scenarios have the necessary data both for input and output, enhancing the overall test automation process.</p><h3>47. How to Use Mouseover in Cypress?</h3><p>In Cypress, simulating a mouseover event can be achieved using the `trigger()` function. This is particularly useful for testing interactions that rely on hover states, such as tooltips or dropdown menus. To perform a mouseover, you first need to select the desired element and then trigger the mouseover event. Here’s a basic example:</p><pre>cy.get(&#39;.your-element-selector&#39;).trigger(&#39;mouseover&#39;);</pre><p>In this example, replace `.your-element-selector` with the actual selector for the element you wish to target. Upon triggering the mouseover event, you can then assert the expected outcome, such as checking if a tooltip appears or if a specific style is applied to the element. This helps ensure that the user interface behaves correctly in response to mouse interactions.</p><h3>48. How can I perform drag and drop in Cypress?</h3><p>In Cypress, performing a drag and drop operation can be achieved using the `trigger()` function to simulate the necessary mouse events. While Cypress does not natively support drag and drop, you can replicate it by triggering the appropriate events in sequence: `mousedown`, `mousemove`, and `mouseup`. Here’s an example of how you can implement a simple drag-and-drop action:</p><pre>cy.get(&#39;.draggable-element&#39;)<br>.trigger(&#39;mousedown&#39;, { which: 1 });<br>cy.get(&#39;.drop-zone&#39;)<br>.trigger(&#39;mousemove&#39;)<br>.trigger(&#39;mouseup&#39;, { force: true });</pre><p>In this code snippet, replace `.draggable-element` with the selector for the item you want to drag, and `.drop-zone` with the selector for where you want to drop it. The `{ force: true }` option ensures that the mouseup event is triggered even if Cypress detects that the target isn’t interactable, allowing for more flexible interactions in your tests.</p><h3>49. How can you click on the button in Cypress?</h3><p>To click on a button in Cypress, you can use the `.click()` command in conjunction with a selector that identifies the button you want to interact with. A simple example would be using a class, ID, or any other attribute to locate the button. Here’s a basic demonstration:</p><pre>cy.get(&#39;button#submit&#39;).click();</pre><p>In this case, `cy.get(‘button#submit’)` selects the button with the ID “submit,” and the `.click()` method simulates a click action on that button. You can also add assertions after the click to verify the expected outcome, ensuring your tests confirm the button’s functionality effectively.</p><h3>50. How to click hidden element in Cypress?</h3><p>To click a hidden element in Cypress, you can use the `{ force: true }` option with the `cy.click()` command. This will bypass the visibility check and allow you to interact with the element regardless of its visibility state.</p><pre>cy.get(&#39;selector-for-hidden-element&#39;).click({ force: true });</pre><h3>51. What is the trigger function in Cypress?</h3><p>The `.trigger()` function in Cypress is used to programmatically simulate an event on a DOM element. This can be particularly useful for testing how your application handles specific user interactions without requiring physical user input.</p><p><strong>Example:</strong></p><p>Consider the following HTML code:</p><pre>&lt;button id=&quot;submit&quot;&gt;Submit&lt;/button&gt;</pre><p>In your test script, if you want to simulate a click event on the button, you can use:</p><pre>cy.get(&#39;#submit&#39;).trigger(&#39;click&#39;);</pre><p>This command will trigger the click event on the button with the ID `submit`, allowing you to test the associated functionality, such as form submission or any other actions triggered by that click.</p><h3>52. How do you change the baseUrl in Cypress dynamically?</h3><p>To change the `baseUrl` in Cypress dynamically, you can leverage environment variables. By defining the `baseUrl` in your `cypress.json` file under the `env` section, you can override it during your test runs. Here’s how you can do it:</p><p><strong>Set the baseUrl in ‘cypress.json’:</strong></p><pre>{<br>&quot;env&quot;: {<br>&quot;baseUrl&quot;: &quot;http://localhost:3000&quot;<br>}<br>}</pre><p><strong>Run Cypress with a specific baseUrl:</strong></p><p>You can specify a different `baseUrl` using command line arguments when running your tests. For example:</p><pre>cypress run --env baseUrl=&quot;http://www.softwaretestingmaterial.com&quot;</pre><p><strong>Access the baseUrl in your tests:</strong></p><p>You can then access this dynamically set `baseUrl` in your tests using `Cypress.env()`. For example:</p><pre>cy.visit(Cypress.env(&#39;baseUrl&#39;));</pre><p>By following these steps, you can easily adjust the `baseUrl` for different environments without needing to hard-code values directly into your tests.</p><h3>53. How to get the title of the page in Cypress?</h3><p>To retrieve the title of the current page in Cypress, you can use the following command:</p><pre>cy.title().then((title) =&gt; {<br>cy.log(title);<br>});</pre><p>This will log the title to the Cypress console for verification.</p><h3>54. How to use Sleep in Cypress?</h3><p>To introduce a delay in your tests, you can use the `.wait()` command in Cypress, which pauses execution for a specified duration in milliseconds. For example, `cy.wait(2000);` will sleep for 2 seconds before proceeding to the next command.</p><h3>55. What is an Environment Variable in Cypress?</h3><p>Environment variables in Cypress are a powerful feature that allows developers to manage different values for their tests without hardcoding them. These variables can be used to store sensitive information, like API keys or database credentials, as well as configuration settings that might change between development, staging, and production environments.</p><p>In Cypress, environment variables can be defined in the `cypress.json` file, provided through command-line arguments, or set directly in the Cypress dashboard. By using environment variables, you can ensure that your test scripts remain flexible and secure, making it easier to adapt them to various scenarios without making changes to the actual code. For example, you can access an environment variable in your test with `Cypress.env(‘variableName’)`.</p><h3>56. How can I type Keypress in Cypress?</h3><p>To simulate a keypress in Cypress, you can use the `.type()` command along with the desired key combination. For example, to type a specific key like “Enter” after entering a value, you can do it as follows:</p><pre>cy.get(&#39;input&#39;).type(&#39;Hello{enter}&#39;);</pre><p>This will enter “Hello” into the input field and then simulate pressing the Enter key.</p><h3>57. How to read a value form Cypress configuration file?</h3><p>To read a value from the Cypress configuration file, you can use the `Cypress.config()` method. For example, to access the base URL, you would use `const baseUrl = Cypress.config(‘baseUrl’);`.</p><h3>58. How to create suites in Cypress?</h3><p>Creating test suites in Cypress is essential for organizing your tests logically and efficiently. A test suite can be created by grouping multiple tests using the `describe` function, which allows you to define a specific category of tests related to a common functionality or feature. Here’s a basic example of how to form a test suite:</p><pre>describe(&#39;User Login Suite&#39;, () =&gt; {<br>    it(&#39;should successfully log in with valid credentials&#39;, () =&gt; {<br>        // Your test code here<br>    });<br>    it(&#39;should show an error message for invalid credentials&#39;, () =&gt; {<br>        // Your test code here<br>    });<br>});</pre><p>Within each `describe` block, you can define multiple `it` blocks, each representing a standalone test case. This structure not only improves readability but also facilitates easier management of your tests, allowing for better debugging and reporting.</p><h3>59. How to run a single specfile in command line?</h3><p>To execute a single spec file using Cypress from the command line, you can utilize the following command structure:</p><pre>npx cypress run --spec &quot;cypress/integration/your-spec-file.js&quot;</pre><p>Replace `”cypress/integration/your-spec-file.js”` with the path to the specific spec file you wish to run. This command enables you to focus on running only the tests contained within that file, streamlining your testing process and saving time, especially during development and debugging phases. Additionally, you can specify the browser you want to use by adding `–browser chrome` (or `–browser firefox`, etc.) to the command if needed.</p><h3>60. Name some commands which you use to interact with DOM elements?</h3><p>Some common cypress commands used to interact with DOM elements are as follows:</p><ul><li><strong>‘cy.get(selector)</strong>‘ — Retrieves one or more DOM elements matching the specified selector.</li><li><strong>‘cy.contains(text)’</strong> — Finds a DOM element containing specific text.</li><li><strong>‘cy.click()</strong>‘ — Simulates a mouse click on the selected element.</li><li><strong>‘cy.dblclick()</strong>‘ — Simulates a double-click action on the selected element.</li><li><strong>‘cy.rightclick()’</strong> — Simulates a right-click action on the selected element.</li><li><strong>‘cy.type(text)</strong>‘ — Types text into an input field.</li><li><strong>‘cy.select(value)’</strong> — Selects an option from a dropdown menu by its value.</li><li><strong>‘cy.clear()’</strong> — Clears the value of an input field.</li><li><strong>‘cy.check()’</strong> — Checks a checkbox or radio button by selecting it based on its value or label.</li><li><strong>‘cy.uncheck()’</strong> — Unchecks a checkbox or radio button that is currently selected.</li><li><strong>‘cy.visible()</strong>‘ — Checks if an element is visible in the viewport.</li><li><strong>‘cy.should(condition)’</strong> — Asserts that a DOM element meets a specified condition (e.g., be.visible, exist).</li><li><strong>‘cy.focus()</strong>‘ — Sets focus on the selected element.</li><li><strong>‘cy.hover()’</strong> — Simulates hovering over a DOM element.</li></ul><h3>61. How to get the first and last child of the selected element?</h3><p>In Cypress, you can easily access the first and last child of a selected element using the `.children()` method combined with the `.first()` and `.last()` methods. Here’s how you can do it:</p><pre>// Assuming you have a parent element selected<br>cy.get(&#39;parent-selector&#39;).children().first().should(&#39;have.text&#39;, &#39;Expected First Child Text&#39;);<br>cy.get(&#39;parent-selector&#39;).children().last().should(&#39;have.text&#39;, &#39;Expected Last Child Text&#39;);</pre><p>In this example, replace `’parent-selector’` with the actual CSS selector of the parent element from which you want to retrieve the first and last children. The `.should()` command helps in verifying the text or any other property of the child elements.</p><h3>62. How can we use Browser Navigation in Cypress?</h3><p>Cypress provides several commands that allow us to control browser navigation effectively. These commands include `cy.visit()`, which navigates to a specified URL, and `cy.go()`, which can move backward or forward in the browser’s history. For instance, to visit a specific webpage, you can use the following code:</p><pre>cy.visit(&#39;http://example.com&#39;);</pre><p>To go back to the previous page in the browser history, you can simply call:</p><pre>cy.go(&#39;back&#39;);</pre><p>Conversely, to go forward, use:</p><pre>cy.go(&#39;forward&#39;);</pre><p>Furthermore, Cypress allows us to reload the current page using:</p><pre>cy.reload();</pre><p>These navigation commands can streamline your testing process by simulating user interactions more accurately, ensuring your application behaves as expected when users navigate through it.</p><h3>63. How to press keyboard keys in Cypress?</h3><p>Cypress provides a straightforward way to simulate keyboard interactions in your tests through the `.type()` command. This command can be used not only for entering text in input fields but also for pressing specific keys. Here’s how you can do it:</p><p>To type a string into a field, use the following syntax:</p><pre>cy.get(&#39;input&#39;).type(&#39;Hello, World!&#39;);</pre><p>If you want to simulate pressing special keys like `Enter`, `Escape`, or `Tab`, you can pass the key as a string. For example:</p><pre>// Press the Enter key<br>cy.get(&#39;input&#39;).type(&#39;{enter}&#39;);<br>// Press the Escape key<br>cy.get(&#39;input&#39;).type(&#39;{esc}&#39;);<br>// Press the Tab key<br>cy.get(&#39;input&#39;).type(&#39;{tab}&#39;);</pre><p>These commands can be combined with other actions to create more complex interactions. Remember to ensure that the targeted element is in focus before simulating key presses for accurate results.</p><h3>64. What is Shadow DOM in Cypress and how do you access Shadow DOM in Cypress?</h3><p>Shadow DOM is a web standard that allows developers to encapsulate a piece of the DOM and its styles, preventing them from being affected by the rest of the page. This encapsulation is particularly useful for web components, as it promotes better component reuse and isolation. In Cypress, to access elements within a Shadow DOM, you can use the `.shadow()` command. Here’s how to do it:</p><pre>cy.get(&#39;element-with-shadow-root&#39;).shadow().find(&#39;child-element&#39;);</pre><p>In this example, `element-with-shadow-root` is the host element that contains the shadow DOM, and `child-element` is the element you wish to access within that shadow DOM. This method allows you to interact seamlessly with elements that are encapsulated by the Shadow DOM in your testing scenarios.</p><h3>65. How to Test Iframes with Cypress?</h3><p>Testing iframes in Cypress can be a bit challenging since Cypress commands do not automatically access elements within an iframe due to the way it executes in a single DOM context. However, you can still interact with iframes by using a combination of Cypress commands and a custom function. First, you need to get the iframe’s content and then use it to perform further actions. Here’s how you can achieve that:</p><pre>cy.get(&#39;iframe&#39;)<br>  .its(&#39;0.contentDocument.body&#39;) // Access the iframe&#39;s body<br>  .then(cy.wrap) // Wrap it so Cypress can interact with it<br>  .find(&#39;input[name=&quot;iframeInput&quot;]&#39;) // Find the desired input element within the iframe<br>  .type(&#39;Hello from Cypress!&#39;); // Type into the input field</pre><p>In this example, we first get the iframe, access its body, and then wrap it so we can search for elements inside the iframe context. This approach allows you to effectively test and interact with elements contained within an iframe in your Cypress tests.</p><p>Also, You can enhance your work with elements inside an iframe by using the <a href="https://www.npmjs.com/package/cypress-iframe?ref=cypress-io.ghost.io">Cypress iframes plugin</a>, which provides custom commands for simplification.</p><p>Below is a basic example that demonstrates how to interact with an input field inside an iframe using this plugin.</p><p>First, ensure you have installed the plugin:</p><pre>npm install -D cypress-iframe</pre><p>Then, you can write a test script as follows:</p><pre>describe(&#39;Iframe Test Example&#39;, () =&gt; {<br>  it(&#39;should type into an iframe input field&#39;, () =&gt; {<br>    cy.visit(&#39;/your-page-with-iframe&#39;); // Replace with the URL of your page<br>    cy.frameLoaded(&#39;iframe.selector&#39;); // Load the iframe<br>    cy.iframe(&#39;iframe.selector&#39;) // Select the iframe<br>      .find(&#39;input[name=&quot;iframeInput&quot;]&#39;) // Find the input field within the iframe<br>      .type(&#39;Hello from Cypress Frames Plugin!&#39;); // Type into the input field<br>  });<br>});</pre><p>In this example, we first visit the page that contains the iframe. We then use the `cy.frameLoaded()` command to ensure the iframe is loaded before interacting with its content. Finally, we select the iframe and find the input field to type a message. This straightforward approach makes working with iframes much easier in your Cypress tests.</p><h3>66. How to execute JavaScript commands in Cypress?</h3><p>Executing JavaScript commands in Cypress is straightforward thanks to its built-in `cy.window()` command, which gives you access to the window object of the browser. This enables you to run any JavaScript directly within the context of your application. For example, to execute a simple command, you can do the following:</p><pre>cy.window().then((win) =&gt; {<br>// Run any JavaScript command here<br>const result = win.someGlobalFunction(); // Example of calling a global function<br>cy.log(result); // Log the result<br>});</pre><p>This method allows you to interact with the application’s JavaScript, access global variables, or even perform assertions based on the results obtained from executing JavaScript commands.</p><h3>67. Can we use BDD with Cypress?</h3><p>Yes, we can use Behavior-Driven Development (BDD) with Cypress, which is particularly useful for writing tests in a more readable and understandable format. Cypress supports BDD syntax through frameworks like Mocha and Chai, allowing developers to write tests using Given-When-Then language. By integrating Cypress with tools like Cucumber, you can create feature files that articulate the desired behavior of your application in plain language, while Cypress handles the underlying test execution. This combination enhances collaboration among team members, making it easier for non-technical stakeholders to comprehend test scenarios and ensuring that requirements are met effectively.</p><h3>68. How can we filter the DOM element?</h3><p>In Cypress, filtering DOM elements is achieved using various methods that help narrow down the selection to specific elements based on certain criteria. One of the most common methods is `.filter()`, which filters a set of elements down to those that match a specified selector. For example, if you have multiple list items and want to select only those with a particular class, you can use:</p><pre>cy.get(&#39;li&#39;).filter(&#39;.active&#39;)</pre><p>This code will return only the list items that have the class <strong>active</strong>. Additionally, you can use `.eq(index)` to select an element at a specific index of the filtered collection, allowing greater control over your element selections. For instance, if you want the first item of a filtered list, you can chain:</p><pre>cy.get(&#39;li&#39;).filter(&#39;.active&#39;).eq(0)</pre><p>Combining these methods enhances your ability to interact with the specific elements you need while writing tests in Cypress.</p><h3>69. What is the before:run event in Cypress?</h3><p>The `before:run` event in Cypress is triggered before any tests are executed within a test suite. This allows developers to perform initial setup tasks or configure certain parameters that should be in place before the tests begin running.</p><p>For instance, it can be used to set environment variables, configure application states, or clear data from previous runs. To listen for this event, you can use the `Cypress.on` syntax, allowing you to add custom logic and enhance the flexibility of your testing process.</p><p>Here’s a simple example:</p><pre>Cypress.on(&#39;before:run&#39;, (details) =&gt; { <br>// Custom logic or setup before running tests <br>console.log(&#39;Tests are about to run&#39;);<br>});</pre><p>This feature is particularly useful for ensuring a clean and controlled testing environment, which can help improve the reliability of your tests.</p><h3>70. What is the after:run event in Cypress?</h3><p>The `after:run` event in Cypress is triggered after all the tests in a test suite have completed execution. This event provides an opportunity for developers to perform cleanup tasks, log results, or execute any final actions that should take place once the tests are finished.</p><p>For example, you might use this event to gather test metrics, generate reports, or reset application states. To listen for this event, you can utilize the `Cypress.on` syntax similarly to the `before:run` event.</p><p>Below is a simple illustration of how to implement this:</p><pre>Cypress.on(&#39;after:run&#39;, (results) =&gt; {<br>// Custom logic or cleanup after tests have run<br>console.log(&#39;Tests have finished running&#39;, results);<br>});</pre><p>Utilizing the `after:run` event effectively can enhance test management and reporting, contributing to a streamlined testing workflow.</p><h3>71. How to handle window alerts in Cypress?</h3><p>Cypress provides a straightforward way to deal with window alerts and prompts. When an alert is triggered, Cypress automatically listens for it and can handle it gracefully. To do this, you can use the `cy.on()` command to catch the alert and respond accordingly. Here’s how you can handle a simple alert:</p><pre>cy.on(&#39;window:alert&#39;, (text) =&gt; {<br>// You can assert the alert message if needed<br>expect(text).to.equal(&#39;Your alert message here&#39;);<br>});</pre><p>Additionally, if you need to handle a confirmation dialog, you can use a similar approach:</p><pre>cy.on(&#39;window:confirm&#39;, () =&gt; true); // Automatically accepts the confirmation</pre><p>By using these commands, you can effectively integrate alert handling into your Cypress tests, ensuring that they run smoothly without being interrupted by unexpected pop-ups.</p><h3>72. How to run tests in Cypress?</h3><p>Running tests in Cypress is a straightforward process that can be accomplished through multiple methods. To begin, ensure that Cypress is installed in your project. You can initiate the Cypress Test Runner with the following command in your terminal:</p><pre>npx cypress open</pre><p>This command opens the Cypress Test Runner interface, allowing you to select and run individual tests easily. You can also run tests headlessly from the command line using:</p><pre>npx cypress run</pre><p>This executes all tests in the specified browser without the graphical interface. Additionally, you can specify particular test files or folders to run by using flags like `–spec`, for example:</p><pre>npx cypress run --spec &#39;cypress/integration/myTest.spec.js&#39;</pre><p>By using these commands, testers can efficiently manage and execute their Cypress tests, ensuring a streamlined testing process.</p><h3>73. How to skip tests in Cypress?</h3><p>In Cypress, you can easily skip tests or specific test cases when needed. This is particularly useful for temporarily disabling a test that may be failing or irrelevant during development. To skip a test, you can use the `it.skip()` method instead of the regular `it()` function. Here’s an example:</p><pre>it.skip(&#39;This test will be skipped&#39;, () =&gt; {<br>// Test code goes here<br>});</pre><p>You can also skip entire test suites using `describe.skip()`:</p><pre>describe.skip(&#39;Skipped Test Suite&#39;, () =&gt; {<br>it(&#39;This test will not run&#39;, () =&gt; {<br>// Test code goes here<br>});<br>});</pre><p>By applying these methods, you can manage your test executions flexibly, maintaining a clean and efficient testing process without running unnecessary or failing tests.</p><h3>74. What is the ‘cy.task()’ function in Cypress?</h3><p>The `cy.task()` function in Cypress is used to execute Node.js code from Cypress test files, allowing you to perform operations that cannot be executed in the browser context. This is particularly useful for tasks such as accessing files, interacting with databases, or carrying out other server-side operations. By using `cy.task()`, you can communicate between your test code and custom tasks defined in the `plugins` file. Here’s an example of how to use `cy.task()` to read a file:</p><pre>// In your plugin file<br>module.exports = (on, config) =&gt; {<br>on(&#39;task&#39;, {<br>readFile(filePath) {<br>return fs.readFileSync(filePath, &#39;utf8&#39;);<br>}<br>});<br>};<br>// In your test file<br>cy.task(&#39;readFile&#39;, &#39;path/to/your/file.txt&#39;).then((content) =&gt; {<br>  console.log(content);<br>});</pre><p>In this example, `cy.task()` is used to call the `readFile` task, which reads the content of a specified file and returns it to the test for further processing.</p><h3>75. What is the ‘cy.exec()’ function in Cypress?</h3><p>The `cy.exec()` function in Cypress allows you to run system commands directly from your test scripts. This is useful for executing shell commands, scripts, or processes that are outside the context of a browser. Using `cy.exec()`, you can automate tasks like starting or stopping a server, running database migrations, or performing any command-line operations needed for your tests. Here’s an example of how to use `cy.exec()` to list the contents of a directory:</p><pre>cy.exec(&#39;ls -la&#39;).then((result) =&gt; {<br>console.log(result.stdout);<br>});</pre><p>In this example, the `exec()` function executes the `ls -la` command, which lists all files and directories in the current working directory. The result is then logged to the console, showcasing the output of the command. Be mindful of the platform you’re running on, as command syntax may vary between operating systems.</p><h3>Conclusion</h3><p>Mastering Cypress is essential for anyone looking to excel in modern web automation testing. By familiarizing yourself with these common interview questions and their answers, you’ll be well-prepared to showcase your expertise and tackle any challenges that come your way.</p><p>Remember, practice makes perfect, so don’t hesitate to dive deeper into Cypress documentation and hands-on projects to further solidify your knowledge. With dedication and the right preparation, you’ll be well-positioned to impress interviewers and advance your career in web testing and development.</p><p>Reference: <a href="https://www.softwaretestingmaterial.com/">https://www.softwaretestingmaterial.com/</a></p><p>===============================================================</p><p>The above information is up to my understanding.</p><p>Thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94f4af7d3752" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Certified Cloud Practitioner-2025: Amazon EC2]]></title>
            <link>https://sudheer-baraker.medium.com/aws-certified-cloud-practitioner-2025-amazon-ec2-ee28b295d9d9?source=rss-f17fb69241fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee28b295d9d9</guid>
            <category><![CDATA[aws-ccp]]></category>
            <category><![CDATA[aws-ec2]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Sudheer]]></dc:creator>
            <pubDate>Wed, 08 Jan 2025 19:22:17 GMT</pubDate>
            <atom:updated>2025-01-08T19:23:21.729Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/667/0*HSIeTkZ0wFWXTTm1.png" /></figure><p>Amazon EC2 is a web service that provides resizable compute capacity in the cloud.</p><p>EC2 = Elastic Compute Cloud = Infrastructure as a Service</p><p>• It mainly consists in the capability of:</p><ol><li>Renting virtual machines (EC2).</li><li>Storing data on virtual drives (EBS)</li><li>Distributing load across machines (ELB)</li><li>Scaling the services using an auto-scaling group (ASG)</li></ol><p><strong>Key Features:</strong></p><ul><li>On-demand scalability for compute resources.</li><li>Ideal for hosting applications, running containers, and more.</li><li>Flexibility to select instance configurations (CPU, memory, storage).</li></ul><p><strong>Use Cases:</strong></p><ul><li>Hosting websites or applications.</li><li>Big data processing.</li><li>Running containerized workloads.</li></ul><h4>EC2 sizing &amp; configuration options</h4><ul><li>Operating System (OS): Linux, Windows or Mac OS</li><li>How much compute power &amp; cores (CPU)</li><li>How much random-access memory (RAM)</li><li><strong>How much storage space:</strong></li></ul><ol><li>Network-attached (EBS &amp; EFS)</li><li>hardware (EC2 Instance Store)</li></ol><ul><li>Network card: speed of the card, Public IP address</li><li>Firewall rules: security group</li><li>Bootstrap script (configure at first launch): EC2 User Data</li></ul><h4>EC2 User Data</h4><ul><li>It is possible to bootstrap our instances using an EC2 User data script.</li><li>bootstrapping means launching commands when a machine starts</li><li>That script is only run once at the instance first start</li><li>EC2 user data is used to automate boot tasks such as: Installing updates and Installing software</li><li>Downloading common files from the internet</li><li>Anything you can think of</li><li>The EC2 User Data Script runs with the root user</li></ul><h4>EC2 Instance Types — Overview</h4><p>EC2 instance types are categorized based on specific workloads, offering a balance of <strong>CPU</strong>, <strong>memory</strong>, <strong>networking</strong>, and <strong>storage</strong> capabilities.</p><p>AWS has the following naming convention:</p><blockquote><strong>m5.2xlarge</strong></blockquote><blockquote>•m: instance class</blockquote><blockquote>•5: generation (AWS improves them over time)</blockquote><blockquote>•2xlarge: size within the instance class</blockquote><ul><li><strong>General Purpose Instances</strong>: Balance of compute, memory, and networking.<br>Example: <strong>t3.micro</strong> for lightweight applications.</li><li><strong>Compute-Optimized Instances</strong>: Ideal for compute-intensive tasks like analytics or gaming.<br>Example: <strong>c5.large.</strong></li><li><strong>Memory-Optimized Instances</strong>: Designed for memory-intensive workloads, such as databases.<br>Example: <strong>r5.large.</strong></li><li><strong>Storage-Optimized Instances</strong>: High-speed, low-latency storage.<br>Example: <strong>i3.large</strong>.</li><li><strong>Accelerated Computing Instances</strong>: Use GPUs for machine learning, gaming, or rendering tasks.<br>Example: <strong>p4d.24xlarge</strong>.</li></ul><h4>Introduction to Security Groups</h4><p>Security Groups act as virtual firewalls for EC2 instances, controlling inbound and outbound traffic.</p><p><strong>Key Features:</strong></p><ul><li>Allow or deny specific types of traffic.</li><li>Rules can be defined for <strong>protocols</strong>, <strong>ports</strong>, and <strong>IP ranges</strong>.</li><li>Operate at the instance level, providing fine-grained security.</li></ul><p><strong>Example Use Case:</strong><br>Allow SSH access (port 22) from specific IP ranges while blocking all other incoming traffic.</p><p><strong>Best Practices:</strong></p><ul><li>Use least privilege access by limiting allowed IP ranges.</li><li>Regularly review and update security group rules.</li></ul><p><strong>Security groups are acting as a “firewall” on EC2 instances</strong></p><p>They regulate:</p><ul><li>Access to Ports</li><li>Authorized IP ranges — IPv4 and IPv6</li><li>Control of inbound network (from other to the instance)</li><li>Control of outbound network (from the instance to other)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oj6MJnF8EmE6AZA5BNVb5w.png" /><figcaption>Security Groups</figcaption></figure><h4>Security Groups Good to know</h4><ul><li>Can be attached to multiple instances</li><li>Locked down to a region / VPC combination</li><li>Does live “outside” the EC2 — if traffic is blocked the EC2 instance won’t see it.</li><li>It’s good to maintain one separate security group for SSH access.</li><li>If your application is not accessible (time out), then it’s a security group issue.</li><li>If your application gives a “connection refused“error, then it’s an application.</li><li>error or it’s not launched.</li><li>All inbound traffic is blocked by default.</li><li>All outbound traffic is authorized by default.</li></ul><h4>Classic Ports to know</h4><ul><li>22 = SSH (Secure Shell) — log into a Linux instance</li><li>21 = FTP (File Transfer Protocol) — upload files into a file share</li><li>22 = SFTP (Secure File Transfer Protocol) — upload files using SSH</li><li>80 = HTTP — access unsecured websites</li><li>443 = HTTPS — access secured websites</li><li>3389 = RDP (Remote Desktop Protocol) — log into a Windows instance</li></ul><h4>EC2 Instances Purchasing Options</h4><ul><li><strong>On-Demand Instances</strong> — short workload, predictable pricing, pay by second.</li><li><strong>Reserved </strong>(1 &amp; 3 years).</li><li><strong>Reserved Instances </strong>— long workloads.</li><li><strong>Convertible Reserved Instances</strong> — long workloads with flexible instances.</li><li><strong>Savings Plans</strong> (1 &amp; 3 years) –commitment to an amount of usage, long workload.</li><li><strong>Spot Instances</strong> — short workloads, cheap, can lose instances (less reliable).</li><li><strong>Dedicated Hosts </strong>— book an entire physical server, control instance placement.</li><li><strong>Dedicated Instances </strong>— no other customers will share your hardware.</li><li><strong>Capacity Reservations</strong> — reserve capacity in a specific AZ for any duration.</li></ul><h4>Which purchasing option is right for me?</h4><ul><li>On demand: coming and staying in resort whenever we like, we pay the full price.</li><li>Reserved: like planning ahead and if we plan to stay for a long time, we may get a good discount.</li><li>Savings Plans: pay a certain amount per hour for certain period and stay in any room type (e.g., King, Suite, Sea View, …).</li><li>Spot instances: the hotel allows people to bid for the empty rooms and the highest bidder keeps the rooms. You can get kicked out at any time.</li><li>Dedicated Hosts: We book an entire building of the resort.</li><li>Capacity Reservations: you book a room for a period with full price even you don’t stay in it</li></ul><h3>EC2 Instance Storage Section</h3><h4>What’s an EBS Volume?</h4><ul><li>An EBS (Elastic Block Store) Volume is a network drive you can attach to your instances while they run.</li><li>It allows your instances to persist data, even after their termination.</li><li>They can only be mounted to one instance at a time (at the CCP level).</li><li>They are bound to a specific availability zone.</li><li>Analogy: Think of them as a “network USB stick”.</li><li>Free tier: 30 GB of free EBS storage of type General Purpose (SSD) or Magnetic per month.</li></ul><h4>EBS — Delete on Termination attribute</h4><ul><li>Controls the EBS behaviour when an EC2 instance terminates</li><li>By default, the root EBS volume is deleted (attribute enabled)</li><li>By default, any other attached EBS volume is not deleted (attribute disabled)</li><li>This can be controlled by the AWS console / AWS CLI</li><li>Use case: preserve root volume when instance is terminated.</li></ul><h4>EBS Snapshots</h4><ul><li>Make a backup (snapshot) of your EBS volume at a point in time.</li><li>Not necessary to detach volume to do snapshot, but recommended.</li><li>Can copy snapshots across AZ or Region.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*agMSxQzH78LQaqILMcf61A.png" /></figure><h4>EBS Snapshots Features</h4><ul><li><strong>EBS Snapshot Archive.</strong> 1. Move a Snapshot to an” archive tier” that is 75% cheaper. 2. Takes within 24 to 72 hours for restoring the archive</li><li><strong>Recycle Bin for EBS Snapshots</strong>. 1. Setup rules to retain deleted snapshots so you can recover them after an accidental deletion. 2. Specify retention (from 1 day to 1 year).</li></ul><h4>AMI Overview</h4><ul><li>AMI = Amazon Machine Image.</li><li>AMI are a customization of an EC2 instance. 1. You add your own software, configuration, operating system, monitoring. 2. Faster boot / configuration time because all your software is pre-packaged.</li><li>AMI are built for a specific region (and can be copied across regions)</li><li>You can launch EC2 instances from: 1. A Public AMI: AWS provided.2. Your own AMI: you make and maintain them yourself. 3. An AWS Marketplace AMI: an AMI someone else made (and potentially sells).</li></ul><h4>AMI Process (from an EC2 instance)</h4><ul><li>Start an EC2 instance and customize it.</li><li>Stop the instance (for data integrity).</li><li>Build an AMI — this will also create EBS snapshots</li><li>Launch instances from other AMIs</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i7ZGYvF9cKzBNQKDn5SY4Q.png" /></figure><h4>EC2 Image Builder</h4><ul><li>Used to automate the creation of Virtual Machines or container images.</li><li>Automate the creation, maintain, validate and test EC2 AMIs.</li><li>Can be run on a schedule (weekly, whenever packages are updated, etc…)</li><li>Free service (only pay for the underlying resources)</li></ul><h4>EC2 Instance Store</h4><ul><li>EBS volumes are network drives with good but “limited” performance.</li><li>If you need a high-performance hardware disk, use EC2 Instance Store.</li><li>Better I/O performance.</li><li>EC2 Instance Store lose their storage if they’re stopped (ephemeral).</li><li>Good for buffer / cache / scratch data / temporary content.</li><li>Risk of data loss if hardware fails</li><li>Backups and Replication are your responsibility.</li></ul><h4>EFS — Elastic File System</h4><ul><li>Managed NFS (network file system) that can be mounted on 100s of EC2.</li><li>EFS works with Linux EC2 instances in multi-AZ</li><li>Highly available, scalable, expensive (3x gp2), pay per use, no capacity planning</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*Vz9BS4uksguiE9OGvr8EYg.png" /></figure><h4>EFS Infrequent Access (EFS-IA)</h4><ul><li>Storage class that is cost-optimized for files not accessed every day.</li><li>Up to 92% lower cost compared to EFS Standard.</li><li>EFS will automatically move your files to EFS-IA based on the last time they were accessed.</li><li>Enable EFS-IA with a Lifecycle Policy.</li><li><strong>Example</strong>: move files that are not accessed for 60 days to EFS-IA</li><li>Transparent to the applications accessing EFS.</li></ul><h4>Amazon FSx — Overview</h4><ul><li>Launch 3rd party high-performance file systems on AWS.</li><li>Fully managed service: 1. FSx for Lustre .2. FSx for Windows File Server.3. FSx for NetApp ONTAP</li></ul><p><strong>Reference: Stephane Maarek</strong></p><p>===============================================================</p><p>The above information is up to my understanding. Suggestions are always welcome.</p><p>Thank you.</p><p>Sudheer Baraker</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee28b295d9d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Certified Cloud Practitioner-2025: IAM Deep Dive]]></title>
            <link>https://sudheer-baraker.medium.com/aws-certified-cloud-practitioner-2025-iam-deep-dive-f33563b57f7f?source=rss-f17fb69241fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/f33563b57f7f</guid>
            <category><![CDATA[aws-practitioner-exam]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Sudheer]]></dc:creator>
            <pubDate>Sat, 04 Jan 2025 08:45:12 GMT</pubDate>
            <atom:updated>2025-01-08T18:51:03.304Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/667/0*ac5eXG4-eUPEroCw.png" /></figure><h4>IAM Users and Groups</h4><p>Amazon Identity and Access Management (IAM) allows you to manage access to AWS services and resources securely.</p><ul><li><strong>IAM </strong>= Identity and Access Management, Global service</li><li><strong>Root account</strong> created by default, shouldn’t be used or shared</li><li><strong>Users </strong>are people within your organization, and can be grouped</li><li><strong>Groups </strong>only contain users, not other groups</li><li><strong>Users </strong>don’t have to belong to a group, and user can belong to multiple groups</li><li><strong>IAM Users:</strong> These represent individuals or applications that need access to AWS resources. Each user gets unique credentials (password or access keys).</li><li><strong>IAM Groups:</strong> Collections of IAM users managed as a single entity. Policies applied to a group are automatically applied to its members, simplifying permissions management.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kdzAPCo5-muXpmWJcNlZpQ.png" /></figure><h4>IAM Permissions</h4><p>Permissions define what actions a user, group, or role can perform on which AWS resources.</p><ul><li><strong>Explicit Deny:</strong> Always overrides any allow permissions.</li><li><strong>Least Privilege Principle:</strong> Grant only the permissions required to complete a task.</li><li>Permissions are managed using <strong>IAM Policies</strong>.</li></ul><h4>IAM Users, Groups, and Permissions Hands-On Example</h4><ol><li>Create a user named DevUser.</li><li>Create a group named DevGroup and attach the AmazonS3FullAccess policy.</li><li>Add DevUser to DevGroup.</li><li>Test permissions by signing in as DevUser and accessing an S3 bucket.</li></ol><h4>IAM Policies and Their Structure</h4><p>IAM Policies are JSON documents defining permissions. Structure includes:</p><p>Consists of</p><ul><li>Version: policy language version, always include “2012–10-17”</li><li>Id: an identifier for the policy (optional)</li><li>Statement: one or more individual statements (required)</li><li>Statements consists of</li><li>Sid: an identifier for the statement (optional)</li><li>Effect: whether the statement allows or denies access (Allow, Deny)</li><li>Principal: account/user/role to which this policy applied to</li><li>Action: list of actions this policy allows or denies</li><li>Resource: list of resources to which the actions applied to</li><li>Condition: conditions for when this policy is in effect (optional)</li></ul><p>Example Policy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*3LKFqMletgzZZx6EVy87mA.png" /></figure><h4>IAM Password Policy</h4><p>Password policies enforce security requirements for user passwords, such as:</p><p>• Strong passwords = higher security for your account</p><p>• In AWS, you can setup a password policy:</p><ol><li>Set a minimum password length</li><li>Require specific character types:</li></ol><p>2.1. including uppercase letters, lowercase letters, numbers, non-alphanumeric characters.</p><ul><li>Allow all IAM users to change their own passwords</li><li>Require users to change their password after some time (password expiration)</li><li>Prevent password re-use</li></ul><h4>IAM Multi-Factor Authentication (MFA)</h4><p>MFA provides an additional layer of security. Users must provide:</p><ul><li>Users have access to your account and can possibly change configurations or delete resources in your AWS account</li><li>You want to protect your Root Accounts and IAM users</li><li>MFA = password you know + security device you own</li><li>Main benefit of MFA: if a password is stolen or hacked, the account is not compromised</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U0piH9xreMhAPOB-VMlDcQ.png" /></figure><h4>IAM MFA Hands-On</h4><ol><li>Log in to the AWS Management Console.</li><li>Go to IAM &gt; Users &gt; Select a user.</li><li>Under the “Security credentials” tab, click “Manage MFA”.</li><li>Choose a device type (virtual or hardware MFA) and complete the setup.</li><li>Test by logging in with MFA enabled.</li></ol><h4>AWS Access Keys, CLI, and SDK</h4><p>To access AWS, you have three options:</p><ol><li><strong><em>AWS Management Console (protected by password + MFA)</em></strong></li><li><strong><em>AWS Command Line Interface (CLI): protected by access keys</em></strong></li><li><strong><em>AWS Software Developer Kit (SDK) — for code: protected by access keys</em></strong></li></ol><ul><li>Access Keys are generated through the AWS Console</li><li>Users manage their own access keys</li><li>Access Keys are secret, just like a password. Don’t share them</li><li>Access Key ID ~= username</li><li>Secret Access Key ~= password</li></ul><h4>AWS CLI Hands-On</h4><ol><li>Install AWS CLI.</li><li>Configure CLI using the aws configure command:</li></ol><ul><li>Provide access key, secret key, region, and output format.</li></ul><ol><li>Run a command like aws s3 ls to list all S3 buckets.</li></ol><h4>IAM Roles for Services</h4><p>IAM Roles grant temporary permissions to entities such as:</p><p>• Some AWS service will need to perform actions on your behalf</p><p>• To do so, we will assign permissions to AWS services with IAM Roles</p><p><strong>Common roles:</strong></p><ol><li>EC2 Instance Roles</li><li>Lambda Function Roles</li><li>Roles for CloudFormation</li></ol><h4>IAM Security Tools</h4><p>IAM offers several tools for monitoring and improving security:</p><ul><li><strong>IAM Access Analyzer:</strong> Identifies resources with public or cross-account access.</li><li><strong>Service Last Accessed Data:</strong> Shows the last time a service was accessed.</li><li><strong>Credential Reports:</strong> Lists all users and the status of their credentials.</li><li><strong>CloudTrail:</strong> Logs all API calls made in your AWS account.</li></ul><h4>IAM Guidelines and Best Practices</h4><ul><li><strong>Use Groups:</strong> Assign permissions to groups instead of individual users.</li><li><strong>Enable MFA:</strong> Require MFA for all accounts, especially root.</li><li><strong>Follow the Least Privilege Principle:</strong> Avoid granting unnecessary permissions.</li><li><strong>Rotate Credentials:</strong> Regularly rotate access keys and passwords.</li><li><strong>Monitor Activity:</strong> Use CloudTrail and Access Analyzer.</li><li><strong>Restrict Root Account Usage:</strong> Use it only for account setup and emergencies.</li><li><strong>Use Policies Strategically:</strong> Combine managed, inline, and customer-managed policies effectively.</li></ul><h4>Shared Responsibility Model for IAM</h4><p>AWS:</p><ul><li>Infrastructure (global network security)</li><li>Configuration and vulnerability analysis</li><li>Compliance validation</li></ul><p>Users</p><ul><li>Users, Groups, Roles, Policies management and monitoring</li><li>Enable MFA on all accounts</li><li>Rotate all your keys often</li><li>Use IAM tools to apply appropriate permissions</li><li>Analyze access patterns &amp; review permissions</li></ul><h4>IAM Section — Summary</h4><ul><li><strong>Users</strong>: mapped to a physical user, has a password for AWS Console</li><li><strong>Groups</strong>: contains users only</li><li><strong>Policies</strong>: JSON document that outlines permissions for users or groups</li><li><strong>Roles</strong>: for EC2 instances or AWS services</li><li><strong>Security</strong>: MFA + Password Policy</li><li><strong>AWS CLI:</strong> manage your AWS services using the command-line</li><li><strong>AWS SDK</strong>: manage your AWS services using a programming language</li><li><strong>Access Keys</strong>: access AWS using the CLI or SDK</li><li><strong>Audit</strong>: IAM Credential Reports &amp; IAM Access Advisor</li></ul><p><strong>Reference: Stephane Maarek</strong></p><p>===============================================================</p><p>The above information is up to my understanding. Suggestions are always welcome.</p><p>Thank you.</p><p>Sudheer Baraker</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f33563b57f7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Certified Cloud Practitioner-2025]]></title>
            <link>https://sudheer-baraker.medium.com/aws-certified-cloud-practitioner-2025-9a398bd1a2fe?source=rss-f17fb69241fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a398bd1a2fe</guid>
            <category><![CDATA[aws-cloud-practitioner]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Sudheer]]></dc:creator>
            <pubDate>Thu, 02 Jan 2025 18:17:13 GMT</pubDate>
            <atom:updated>2025-01-08T18:50:26.395Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*yLOUaANC3-RYV_IRwhonLg.png" /></figure><h3>AWS Certified Cloud Practitioner-2025: Introduction</h3><h3>What is Cloud Computing?</h3><p>Cloud computing refers to the delivery of on-demand computing services-such as servers, storage, databases, networking, software, and analytics -over the internet (“the cloud”). This eliminates the need for organizations to own and manage physical IT infrastructure. Instead, businesses can access these resources on a pay-as-you-go basis.</p><p><strong>Example:</strong> Using a cloud platform like AWS, you can launch virtual machines, store data, or host applications without having to set up physical servers.</p><h3>Problems with Traditional IT Approach</h3><ul><li><strong>High Initial Costs:</strong> Organizations must invest heavily in hardware, software, and maintenance.</li><li><strong>Scalability Issues:</strong> Scaling up requires buying and configuring new hardware, which takes time and money.</li><li><strong>Maintenance Challenges:</strong> IT teams are responsible for managing and securing physical infrastructure.</li><li><strong>Disaster Recovery:</strong> Recovery from data loss or downtime can be slow and costly.</li></ul><h3>The Deployment Models of the Cloud</h3><ul><li><strong>Public Cloud:</strong> Resources are owned and managed by a cloud provider and shared among multiple customers (e.g., AWS, Azure).</li><li><strong>Private Cloud:</strong> Resources are used exclusively by one organization, either on-premises or hosted by a provider.</li><li><strong>Hybrid Cloud:</strong> Combines both public and private clouds, enabling data and applications to be shared between them.</li></ul><p><strong>Example:</strong> A company may use a public cloud for hosting applications while keeping sensitive data in a private cloud.</p><h3>Characteristics of Cloud Computing</h3><ul><li><strong>On-Demand Self-Service:</strong> Users can provision resources without human intervention.</li><li><strong>Broad Network Access:</strong> Accessible from anywhere with an internet connection.</li><li><strong>Resource Pooling:</strong> Resources are shared among multiple users.</li><li><strong>Rapid Elasticity:</strong> Quickly scale resources up or down.</li><li><strong>Measured Service:</strong> Pay only for what you use.</li></ul><h3>Advantages of Cloud Computing</h3><ul><li><strong>Cost Savings:</strong> No need for upfront investments in infrastructure.</li><li><strong>Scalability:</strong> Easily adjust resources to meet demand.</li><li><strong>Global Reach:</strong> Deploy applications in multiple geographic locations.</li><li><strong>High Availability:</strong> Redundant systems ensure minimal downtime.</li><li><strong>Security:</strong> Providers offer advanced security features and compliance certifications.</li></ul><h3>Problems Solved by the Cloud</h3><ul><li>Eliminates the need for expensive hardware.</li><li>Simplifies disaster recovery.</li><li>Enables rapid deployment of applications.</li><li>Reduces IT maintenance efforts.</li><li>Facilitates global collaboration by enabling remote access.</li></ul><h3>Types of Cloud Computing</h3><ul><li><strong>Infrastructure as a Service (IaaS):</strong> Provides virtualized computing resources (e.g., Amazon EC2).</li><li><strong>Platform as a Service (PaaS):</strong> Offers a platform for developing and deploying applications (e.g., AWS Elastic Beanstalk).</li><li><strong>Software as a Service (SaaS):</strong> Delivers software applications over the internet (e.g., AWS WorkSpaces).</li></ul><h3>Examples of Cloud Computing Types</h3><ul><li><strong>IaaS Example:</strong> Launching virtual machines with Amazon EC2.</li><li><strong>PaaS Example:</strong> Building a web app using AWS Elastic Beanstalk.</li><li><strong>SaaS Example:</strong> Using Google Workspace for email and collaboration.</li></ul><h3>Pricing of the Cloud</h3><p>Cloud pricing is typically based on:</p><ul><li><strong>Pay-as-You-Go:</strong> Pay only for resources used.</li><li><strong>Savings Plans:</strong> Commit to consistent usage for a lower price.</li><li><strong>Spot Pricing:</strong> Use spare capacity at discounted rates.</li></ul><h3>AWS Cloud History</h3><ul><li>Launched in 2006, AWS was the first cloud service provider.</li><li>Initially offered services like Amazon S3 (storage) and EC2 (compute).</li><li>Today, AWS has over 200 fully featured services globally.</li></ul><h3>AWS Cloud Use Cases</h3><ul><li><strong>Web Hosting:</strong> Host dynamic websites and applications.</li><li><strong>Big Data Analytics:</strong> Analyze vast amounts of data.</li><li><strong>Machine Learning:</strong> Build, train, and deploy ML models.</li><li><strong>Disaster Recovery:</strong> Store backup data for rapid recovery.</li><li><strong>DevOps:</strong> Automate software development pipelines.</li></ul><h3>AWS Global Infrastructure</h3><p>AWS operates in:</p><ul><li><strong>Regions:</strong> Geographically isolated locations with multiple data centers.</li><li><strong>Availability Zones:</strong> Isolated data centers within a region.</li><li><strong>Edge Locations:</strong> For content delivery and low-latency access.</li></ul><h3>AWS Regions</h3><p>AWS regions are clusters of data centers located worldwide to provide redundancy and fault tolerance. Examples include:</p><ul><li>North America (e.g., US East, US West)</li><li>Europe (e.g., Frankfurt, Ireland)</li><li>Asia Pacific (e.g., Tokyo, Mumbai)</li></ul><h3>How to Choose an AWS Region</h3><ul><li><strong>Proximity:</strong> Select regions close to users for lower latency.</li><li><strong>Cost:</strong> Pricing varies between regions.</li><li><strong>Compliance:</strong> Choose regions that meet local regulations.</li><li><strong>Services:</strong> Not all regions support all AWS services.</li></ul><h3>AWS Availability Zones</h3><p>Availability Zones (AZs) are multiple, isolated data centers within an AWS region. They ensure high availability and fault tolerance.</p><p><strong>Example:</strong> If one AZ goes offline, applications running in another AZ remain unaffected.</p><p><strong>Reference: Stephane Maarek</strong></p><p>===============================================================</p><p>The above information is up to my understanding. Suggestions are always welcome.</p><p>Thank you.</p><p>Sudheer Baraker</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a398bd1a2fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Interview Questions for QA in Cypress and Playwright.]]></title>
            <link>https://sudheer-baraker.medium.com/javascript-interview-questions-for-qa-in-cypress-and-playwright-3ffb6cc4cf7c?source=rss-f17fb69241fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ffb6cc4cf7c</guid>
            <category><![CDATA[cypress]]></category>
            <category><![CDATA[playwrights]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Sudheer]]></dc:creator>
            <pubDate>Tue, 22 Oct 2024 06:36:21 GMT</pubDate>
            <atom:updated>2024-10-22T06:36:21.396Z</atom:updated>
            <content:encoded><![CDATA[<p>Common JavaScript interview questions for QA candidates with experience in Cypress and Playwright.</p><h3>1. Difference Between var, let, and const Keywords in JavaScript:</h3><p><strong>var</strong>:</p><ul><li>Function-scoped or globally scoped (if declared outside a function).</li><li>Allows re-declaration and re-assignment.</li><li>Can be hoisted, but its value remains undefined until the execution reaches the variable assignment.</li></ul><p><strong>let</strong>:</p><ul><li>Block-scoped (confined to the nearest enclosing block, such as a function or a conditional).</li><li>Allows re-assignment, but not re-declaration within the same scope.</li><li>Not hoisted in the same way as var, meaning it cannot be accessed before it is declared.</li></ul><p><strong>const</strong>:</p><ul><li>Also block-scoped.</li><li>Cannot be re-assigned or re-declared after initialization.</li><li>The value must be assigned at the time of declaration. However, it does not make the object or array it points to immutable, only the reference cannot be changed.</li></ul><p>Example:</p><p><em>var x = 10;<br>let y = 20;<br>const z = 30;</em></p><h3>2. Distinctions Between Asynchronous and Synchronous Programming:</h3><p><strong>Synchronous</strong>:</p><ul><li>In synchronous programming, operations are executed sequentially, one after the other. The next operation waits for the previous one to complete before it starts. This can cause delays, especially if an operation takes a long time (e.g., network requests, file system operations).</li></ul><p><strong>Asynchronous</strong>:</p><ul><li>Asynchronous programming allows other operations to continue while waiting for longer tasks to complete. Instead of blocking the next operation, asynchronous tasks run in the background and are completed using callbacks, promises, or async/await.</li></ul><p>JavaScript primarily follows the <strong>asynchronous</strong> pattern, especially for handling I/O operations (like file access or network requests). It uses the event loop to manage these operations efficiently.</p><h3>3. Promises and How They are Effectively Managed in JavaScript:</h3><p><strong>Promises</strong>:</p><ul><li>A Promise in JavaScript represents a value that will be available in the future, allowing asynchronous operations to be handled more cleanly. Promises can either be <strong>fulfilled</strong>, <strong>rejected</strong>, or <strong>pending</strong>.</li></ul><p><strong>Managing Promises</strong>:</p><ul><li>Promises are handled using .then() for success, .catch() for failure, and .finally() for operations that should always run, regardless of the outcome.</li><li><strong>Chaining Promises</strong> allows for sequential asynchronous operations.</li><li><strong>Async/Await</strong> syntax simplifies promise handling by making the code look synchronous while still being non-blocking.</li></ul><p>Example:</p><p><em>let promise = new Promise((resolve, reject) =&gt; {<br> // Some async task<br> if (success) {<br> resolve(“Success!”);<br> } else {<br> reject(“Error!”);<br> }<br>});</em></p><p><em>promise<br> .then(result =&gt; console.log(result))<br> .catch(error =&gt; console.log(error));</em></p><h3>4. Fundamental Differences Between TypeScript and JavaScript:</h3><p><strong>JavaScript</strong>:</p><ul><li>A dynamically typed language where variables do not have types defined, leading to potential runtime errors.</li><li>It is the base language for web development.</li></ul><p><strong>TypeScript</strong>:</p><ul><li>A superset of JavaScript, which introduces static typing, allowing developers to define variable types and catch errors at compile-time rather than runtime.</li><li>It also supports interfaces, enums, generics, and other object-oriented features.</li><li>TypeScript code is compiled to JavaScript for execution in the browser.</li></ul><p>Example in TypeScript:</p><p><em>let name: string = “John”;<br>let age: number = 30;</em></p><h3>5. JavaScript Objects and Functions: Differences and Syntax Utilization:</h3><p><strong>Objects</strong>:</p><ul><li>Objects are collections of key-value pairs, where keys are strings or symbols, and values can be any data type (functions, arrays, etc.).</li><li>Example:</li></ul><p><em>const person = {<br> name: “Alice”,<br> age: 25,<br> greet() {<br> console.log(`Hello, my name is ${this.name}`);<br> }<br>};</em></p><p><strong>Functions</strong>:</p><ul><li>Functions in JavaScript are first-class citizens, meaning they can be assigned to variables, passed as arguments, and returned from other functions.</li><li>Example:</li></ul><p><em>function add(a, b) {<br> return a + b;<br>}</em></p><p><em>const sum = (x, y) =&gt; x + y; // Arrow function</em></p><p><strong>Differences:</strong></p><ul><li>Functions can be methods of an object, but they can also be independent. Objects, on the other hand, are data containers.</li><li>Functions often manipulate data, while objects hold data.</li></ul><h3>6. Programming Exercises: JavaScript Array Methods and String Manipulation:</h3><p><strong>filter()</strong>:</p><ul><li>Used to create a new array with elements that pass a condition.</li></ul><p><em>const numbers = [1, 2, 3, 4, 5];<br>const evenNumbers = numbers.filter(num =&gt; num % 2 === 0);</em></p><p><strong>map()</strong>:</p><ul><li>Applies a function to each element of an array and returns a new array.</li></ul><p><em>const numbers = [1, 2, 3];<br>const squared = numbers.map(num =&gt; num * num);</em></p><p><strong>reduce()</strong>:</p><ul><li>Reduces the array to a single value by applying a function.</li></ul><p><em>const sum = [1, 2, 3, 4].reduce((acc, curr) =&gt; acc + curr, 0);</em></p><p><strong>String Manipulation</strong>:</p><p><em>let str = “Hello, World!”;<br>let upper = str.toUpperCase(); // Convert to uppercase<br>let substring = str.substring(0, 5); // Extract “Hello”</em></p><h3>7. JavaScript OOP Concepts: Classes, Constructors, and export/import:</h3><p><strong>Classes</strong>:</p><ul><li>Introduced in ES6, classes are templates for creating objects.</li><li>Example:</li></ul><p><em>class Car {<br> constructor(brand, model) {<br> this.brand = brand;<br> this.model = model;<br> }<br> <br> drive() {<br> console.log(`Driving a ${this.brand} ${this.model}`);<br> }<br>}</em></p><p><em>const myCar = new Car(“Toyota”, “Corolla”);<br>myCar.drive();</em></p><p><strong>Export/Import</strong>:</p><ul><li>These keywords are used to share code between files.</li><li><strong>export</strong> is used to expose a variable, function, or class to other files.</li><li><strong>import</strong> is used to bring in exports from other files.</li><li>Example:</li></ul><p><em>// module.js<br>export const name = “John”;</em></p><p><em>// main.js<br>import { name } from ‘./module.js’;<br>console.log(name);</em></p><h3>8. Understanding package.json and Node Modules/Dependencies:</h3><p><strong>package.json</strong>:</p><ul><li>A file that contains metadata about the project, such as project name, version, author, and a list of dependencies (external libraries that the project needs).</li></ul><p>Example package.json structure:</p><p><em>{<br> “name”: “my-app”,<br> “version”: “1.0.0”,<br> “main”: “index.js”,<br> “dependencies”: {<br> “express”: “⁴.17.1”<br> },<br> “scripts”: {<br> “start”: “node index.js”<br> }<br>}</em></p><p><strong>Node Modules/Dependencies</strong>:</p><ul><li>These are external libraries or packages that a project requires, which are managed using Node.js. When you install a dependency using npm install, it is stored in the node_modules folder.</li></ul><p>===============================================================</p><p>The above information is up to my understanding. Suggestions are always welcome.</p><p>Thank you.</p><p>Sudheer Baraker</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ffb6cc4cf7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Best Practices for Cypress UI Web Automation Framework]]></title>
            <link>https://sudheer-baraker.medium.com/best-practices-for-cypress-ui-web-automation-framework-12f09f7f8ce9?source=rss-f17fb69241fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/12f09f7f8ce9</guid>
            <category><![CDATA[cypress]]></category>
            <category><![CDATA[cypress-automation]]></category>
            <dc:creator><![CDATA[Sudheer]]></dc:creator>
            <pubDate>Thu, 03 Oct 2024 06:44:50 GMT</pubDate>
            <atom:updated>2024-10-03T06:44:50.398Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why Follow Best Practices in Your Cypress Framework?</h3><p><strong>Best practices</strong> are essential in Cypress UI automation for several reasons:</p><ul><li><strong>Reliability and Stability:</strong> Ensures tests consistently catch bugs early and minimizes flaky results.</li><li><strong>Maintainability:</strong> Simplifies updating and scaling the test suite as the application evolves.</li><li><strong>Code Readability and Collaboration:</strong> Enhances team efficiency by promoting clear and understandable code.</li><li><strong>Reusability and Modularity:</strong> Facilitates the reuse of test components, reducing redundancy.</li><li><strong>Performance:</strong> Optimizes test execution speed and integrates seamlessly with CI/CD pipelines.</li><li><strong>Cost Efficiency:</strong> Lowers long-term maintenance costs by creating cleaner, easier-to-debug code.</li><li><strong>Cross-Browser Compatibility:</strong> Ensures tests run smoothly across different browsers and environments.</li></ul><h3>Cypress Best Practices</h3><h3>1. Framework Design and Structure</h3><p><strong>Layered Architecture:</strong> Implement a layered design to separate concerns, enhancing clarity and maintainability.</p><ul><li><strong>Test Layer:</strong> Contains test scenarios and business logic.</li><li><strong>Service/Business Layer:</strong> Manages interactions between tests and UI elements.</li><li><strong>UI Interaction Layer:</strong> Handles page interactions using the <strong>Page Object Model (POM)</strong>.</li></ul><p><strong>Page Object Model (POM):</strong> Use POM to create an object repository for UI elements. This centralizes element locators, making the framework more maintainable and adaptable to UI changes.</p><p><strong>Sample Framework Structure for Cypress:</strong></p><pre>/cypress-automation-framework<br>├── /cypress<br>│   ├── /fixtures<br>│   ├── /e2e<br>│   │   ├── /tests<br>│   ├── /plugins<br>│   ├── /support<br>│   │   ├── commands.js<br>│   │   ├── e2e.js<br>│   └── /pages<br>│       ├── LoginPage.js<br>│       ├── HomePage.js<br>├── /reports<br>├── /logs<br>├── /docs<br>├── cypress.json<br>├── package.json<br>└── README.md</pre><h3>2. Choosing the Right Tools</h3><ul><li><strong>Framework/Library Selection:</strong> Cypress is an excellent choice for modern web applications. Leverage Cypress-specific plugins for enhanced functionality.</li><li><strong>Cross-Browser Testing:</strong> While Cypress primarily supports Chrome-family browsers, utilize tools like Cypress Cross Browser Testing or integrate with services like BrowserStack for broader browser coverage.</li></ul><h3>3. Locator Strategy</h3><ul><li><strong>Stable Locators:</strong> Use unique selectors such as data-testid, data-cy, or stable class names. Avoid selectors that are likely to change (e.g., dynamically generated IDs).</li><li><strong>Fallback Locators:</strong> Implement secondary locators to handle cases where primary selectors may fail.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*xgZvTdwcWxZtzOsekKuLeA.png" /></figure><h3>4. Synchronization and Wait Strategies</h3><ul><li><strong>Implicit Waits with Cypress Commands:</strong> Cypress automatically waits for elements to appear. Utilize commands like cy.get() which include built-in retries.</li><li><strong>Avoid </strong><strong>cy.wait() with Fixed Timeouts:</strong> Instead of using cy.wait(5000), wait for specific conditions.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*30lJ7-KBPXFZIy1dyixcZQ.png" /></figure><h3>5. Test Data Management</h3><ul><li><strong>Externalize Test Data:</strong> Store test data in the /fixtures folder using JSON or other supported formats.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*on6rqDGytYonqKs6m4zwug.png" /></figure><ul><li><strong>Data-Driven Testing:</strong> Utilize fixture data to run tests with multiple data sets.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*CRljVjZKCJ7-PsTmy-EXIw.png" /></figure><h3>6. Handle Dynamic Elements and UI Flakiness</h3><ul><li><strong>Dynamic Elements:</strong> Use resilient selectors and Cypress commands that wait for elements to be ready.</li><li><strong>Retry Logic:</strong> Cypress inherently retries commands until they pass or time out, reducing the need for explicit retry mechanisms.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*3rWIiY8MgX8iaUd7I46CIQ.png" /></figure><h3>7. Robust Exception Handling</h3><ul><li><strong>Error Handling:</strong> Utilize Cypress’s .on(&#39;fail&#39;) to handle errors gracefully and capture screenshots.</li><li><strong>Graceful Failures:</strong> Ensure that one failing test does not halt the entire test suite by structuring tests independently.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*frs5zDz_a4JWBK7-LdA_Jw.png" /></figure><h3>8. Test Execution Strategies</h3><ul><li><strong>Parallel Execution:</strong> Use Cypress Dashboard to run tests in parallel across multiple machines, speeding up test suites.</li><li><strong>Continuous Integration (CI):</strong> Integrate Cypress with CI tools like Jenkins, GitLab CI, or CircleCI to automate test runs on code commits or deployments.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*0zJjwXSZMxao6rUjsfASkA.png" /></figure><h3>9. Maintainable Test Cases</h3><ul><li><strong>Atomic Test Cases:</strong> Write small, focused tests that validate specific functionalities.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*5KixEmiHaPxu4rFcN6bYzA.png" /></figure><ul><li><strong>Avoid Dependencies:</strong> Ensure tests do not rely on the execution order. Each test should set up its own state.</li><li><strong>Clear Naming Conventions:</strong> Use descriptive names for tests and functions.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*AeFoOA_SuOf0VCGWSkF1nw.png" /></figure><h3>10. Reporting and Logging</h3><ul><li><strong>Comprehensive Reporting:</strong> Integrate with reporting tools like <a href="https://www.npmjs.com/package/cypress-allure-plugin">Allure</a> or use Cypress’s built-in reporters for detailed test reports.</li><li><strong>Detailed Logs:</strong> Utilize Cypress’s logging capabilities and custom commands to capture detailed information during test execution.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*Y4HHCnR_1EMo1CkoXaNbrQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*ZdLra3mumXUKtLETuDKCGw.png" /></figure><h3>11. Cross-Browser and Cross-Platform Testing</h3><ul><li><strong>Cross-Browser Compatibility:</strong> Leverage Cypress’s support for Chromium, Firefox, and Edge. For broader coverage, integrate with cloud services like BrowserStack.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*VIPnfc4diY6QEk0kt_hd2Q.png" /></figure><ul><li><strong>Responsive Testing:</strong> Use Cypress commands to test responsive designs by setting viewport sizes.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*kq7Pwo2mi0AVWoFQmVKz1Q.png" /></figure><h3>12. Version Control and Collaboration</h3><ul><li><strong>Version Control:</strong> Store all test scripts, configurations, and documentation in a Git repository to track changes and collaborate effectively.</li><li><strong>Code Reviews:</strong> Implement regular code reviews to maintain code quality and share knowledge among team members.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*bRtZiXDihP0KBcseOPe_0A.png" /></figure><h3>13. Handling Pop-ups, Alerts, and IFrames</h3><ul><li><strong>Pop-ups and Alerts:</strong> Use Cypress commands to handle browser alerts and confirmations.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*aj2rVRNrys_PcAHob_9HsQ.png" /></figure><ul><li><strong>IFrames:</strong> Utilize Cypress plugins like <a href="https://www.npmjs.com/package/cypress-iframe">cypress-iframe</a> to interact with iframes.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*fRrmW_KCjPX6BCcIoljYzg.png" /></figure><h3>14. Maintainability and Scalability</h3><ul><li><strong>Reusable Methods:</strong> Create custom Cypress commands for common actions to promote reusability.</li><li><strong>Refactor Regularly:</strong> Continuously improve and optimize test code to align with application changes and best practices.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*PU8f2ufuScfvf-y883EAPw.png" /></figure><h3>15. Performance Testing</h3><ul><li><strong>Basic Performance Metrics:</strong> Measure page load times and other performance indicators using Cypress commands and plugins.</li><li><strong>Integration with Performance Tools:</strong> Combine Cypress with tools like <a href="https://github.com/paulirish/lighthouse-ci">Lighthouse</a> for deeper performance insights.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*bFCXKtdHVAL6OajvJJ-zWw.png" /></figure><h3>16. Security and Access Management</h3><ul><li><strong>Secure Credentials:</strong> Store sensitive information in environment variables or use Cypress’s Cypress.env to manage secrets securely.</li><li><strong>Role-Based Testing:</strong> Test different user roles by setting appropriate credentials and permissions.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*Aly10o2a7yz8NWkJ_fWebQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*eza-lT5uDCdFgNwh70AFNA.png" /></figure><h3>17. Test Coverage</h3><ul><li><strong>Smoke and Sanity Testing:</strong> Implement smoke tests for critical functionalities and sanity tests for specific components after updates.</li><li><strong>Regression Testing:</strong> Maintain a comprehensive suite of regression tests to ensure new changes do not introduce bugs.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*R0wLPrPN_Sw220ZA9XsvYA.png" /></figure><h3>18. Handle Browser Differences</h3><ul><li><strong>Cross-Browser Testing:</strong> Ensure tests run seamlessly across supported browsers by utilizing Cypress’s multi-browser capabilities or integrating with cloud-based platforms for broader coverage.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*doBGuOHgdw2dyTFP4rMABw.png" /></figure><ul><li><strong>Browser-Specific Handling:</strong> Implement conditional logic if certain tests require browser-specific adjustments.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*eHyA-X6AfEQwtlSvT3Eu9g.png" /></figure><h3>19. Test Maintenance</h3><ul><li><strong>Regular Updates:</strong> Update tests to reflect UI changes, new features, and modifications in business logic.</li><li><strong>Monitor Flakiness:</strong> Identify and fix flaky tests by analyzing test runs and addressing underlying issues like unstable selectors or timing problems.</li></ul><h3>20. Documentation</h3><ul><li><strong>Comprehensive Documentation:</strong> Maintain up-to-date documentation covering framework setup, test execution, adding new tests, and troubleshooting.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*PazYrcvWqIkEVC0wnezDqQ.png" /></figure><ul><li><strong>Test Case Documentation:</strong> Document individual test cases with clear descriptions, steps, expected results, and test data.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*1l-XlymZcHMVmXnJr4Fhqg.png" /></figure><h3>Detailed Cypress Framework Structure</h3><p>Adopting a well-organized folder structure enhances the maintainability and scalability of your Cypress tests. Below is a recommended structure tailored for Cypress UI automation:</p><pre>/cypress-automation-framework<br>├── /cypress<br>│   ├── /fixtures<br>│   │   ├── userData.json<br>│   │   └── productData.json<br>│   ├── /e2e<br>│   │   ├── /tests<br>│   │   │   ├── login.spec.js<br>│   │   │   ├── dashboard.spec.js<br>│   │   │   └── ...<br>│   ├─<br>│   │   └<br>│   ├── /support<br>│   │   ├── commands.js<br>│   │   ├── e2e.js<br>│   │   └── utils.js<br>│   └── /pages<br>│       ├── LoginPage.js<br>│       ├── DashboardPage.js<br>│       └── ...<br>├── /reports<br>│   └── mochawesome<br>├── /logs<br>│   └── test-log.log<br>├── /docs<br>│   ├── setup-guide.md<br>│   ├── test-strategy.md<br>│   └── ...<br>├── cypress.json<br>├── package.json<br>├── package-lock.json<br>└── README.md</pre><h3>Folder Breakdown</h3><ul><li><strong>/cypress</strong></li><li><strong>/fixtures:</strong> Store external test data such as JSON files used for data-driven testing.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*LBxoxBUecVcSi4JBnKjE9Q.png" /></figure><ul><li><strong>/e2e:</strong> Contains all test files organized into subfolders for better structure.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*OHY1hHEdwE-9MHsgPa6G7g.png" /></figure><ul><li><strong>/support:</strong> Contains reusable utilities, custom commands, and global configurations.</li><li><strong>commands.js:</strong> Define custom Cypress commands to encapsulate repetitive actions.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*nUvSigFyc2Xg2oksg_KAUw.png" /></figure><ul><li><strong>e2e.js:</strong> Automatically loaded before test files, used to import custom commands and global configurations.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*pbgB6Djh_fUqThaoVADNSA.png" /></figure><ul><li><strong>utils.js:</strong> Utility functions used across tests.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*uO1Tq-CsEofnHGoV92Bxgw.png" /></figure><ul><li><strong>/pages:</strong> Implement the Page Object Model by creating classes representing different pages or components.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*XiihkGMDfJK__A8FQbpeCQ.png" /></figure><h3>Configuration Files</h3><ul><li><strong>cypress.config.json:</strong> Cypress configuration file where you can set base URL, viewport sizes, reporter settings, and more.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*iBW6eccUw0hBt-57frhIPg.png" /></figure><ul><li><strong>package.json:</strong> Manage dependencies, scripts, and project metadata.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*TTaqHZmvXddFHmuuu6uNWw.png" /></figure><h3>Additional Folders</h3><ul><li><strong>/reports:</strong> Store generated test reports. Integrate with tools like Mochawesome for enhanced reporting.</li><li><strong>/logs:</strong> Keep log files for debugging purposes.</li><li><strong>/docs:</strong> Maintain documentation related to the framework, including setup guides, test strategies, and coding standards.</li></ul><h3>Implementing the Cypress Framework Structure</h3><p>Here’s a step-by-step guide to setting up the recommended Cypress framework structure:</p><h3>Step 1: Initialize Your Project</h3><ol><li><strong>Create Project Directory:</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*o0UMmdW_aa_rm4fDZAFIHQ.png" /></figure><p><strong>2. Initialize npm:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*EU4x7ZNf-bVZ8Oq3yKTEZA.png" /></figure><h3>Step 2: Install Cypress and Dependencies</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*MLmCLf8q4Z8vPpV9JNwUEw.png" /></figure><h3>Step 3: Configure Cypress</h3><ol><li><strong>Open Cypress for the First Time:</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*mi6RJly5msmb6fogcTaqoQ.png" /></figure><p>This command creates the initial Cypress folder structure.</p><p><strong>2. Modify </strong><strong>cypress.config.json to Include Reporting Configuration:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*MXXAhkMzwh5K_T-cXA6veg.png" /></figure><h3>Step 4: Organize Folder Structure</h3><p>Create the necessary folders based on the recommended structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*hMvUTUa9vPEJYNg8gfONRA.png" /></figure><h3>Step 5: Implement Page Object Model (POM)</h3><p>Create page classes in the /cypress/pages directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*0rzIBSVh75uN6VxKglZVeg.png" /></figure><h3>Step 6: Create Custom Commands</h3><p>Define reusable commands in cypress/support/commands.js.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*SVck4ExNLg9chSLsAPfixw.png" /></figure><h3>Step 7: Write Your First Test</h3><p>Create a test file in cypress/e2e/tests/login.spec.js.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*oRXvHVl9EmKyphsqVccbxQ.png" /></figure><h3>Step 8: Configure Reporting Scripts</h3><p>Add scripts to package.json for generating reports.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*cRBS4GBKKAJtD-tIhqkomA.png" /></figure><h3>Step 9: Run Tests and Generate Reports</h3><ol><li><strong>Run Tests:</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*od1vGFvMH_3cThUmQSkPNQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*4JjP2ca1mN1zBEMtw7DnOg.png" /></figure><p>This will create a comprehensive HTML report in the /reports directory.</p><h3>Additional Tips for Cypress Best Practices</h3><ul><li><strong>Use Environment Variables:</strong> Manage different environments (development, staging, production) by setting environment variables in cypress.config.json or using .env files with <a href="https://www.npmjs.com/package/cypress-dotenv">cypress-dotenv</a>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*ElDOhOuZg4_GDMXpmiPkHQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*05DwHof2ktxY1J9g1C7cQA.png" /></figure><ul><li><strong>Leverage Cypress Plugins:</strong> Enhance functionality with plugins like <a href="https://www.npmjs.com/package/cypress-axe">cypress-axe</a> for accessibility testing or <a href="https://www.npmjs.com/package/cypress-image-snapshot">cypress-image-snapshot</a> for visual regression.</li><li><strong>Implement Continuous Feedback:</strong> Use Cypress Dashboard for real-time insights and analytics on your test runs.</li><li><strong>Adopt TypeScript:</strong> For better type safety and enhanced development experience, consider writing your Cypress tests in TypeScript.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*P6SDroHu2_0cUqTp1QqNcw.png" /></figure><ul><li>Configure TypeScript in tsconfig.json and rename your test files to .ts.</li><li><strong>Regularly Update Cypress:</strong> Keep Cypress and its dependencies up to date to leverage the latest features and security patches.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*54R50cRR4Ab0gy63_oG-Ag.png" /></figure><p>By following these <strong>Cypress-specific best practices</strong> and maintaining a well-organized framework structure, you’ll create a robust, scalable, and efficient UI automation suite that enhances your development workflow and ensures high-quality software delivery.</p><p>===============================================================</p><p>The above information is up to my understanding. Suggestions are always welcome.</p><p>Thank you.</p><p>Sudheer Baraker</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12f09f7f8ce9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Essential JavaScript Programs for Automation Interviews]]></title>
            <link>https://sudheer-baraker.medium.com/essential-javascript-programs-for-automation-interviews-7445bb41afde?source=rss-f17fb69241fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/7445bb41afde</guid>
            <category><![CDATA[javascript-interview]]></category>
            <dc:creator><![CDATA[Sudheer]]></dc:creator>
            <pubDate>Tue, 01 Oct 2024 17:55:36 GMT</pubDate>
            <atom:updated>2024-10-01T17:55:36.003Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. Reverse a String using a Loop</h3><pre>function reverseString(str) {<br>  // Initialize an empty string to store the reversed result<br>  let reversed = &#39;&#39;;<br>  <br>  // Loop through the string from the last character to the first<br>  for (let i = str.length - 1; i &gt;= 0; i--) {<br>    // Add each character to the reversed string<br>    reversed += str[i];<br>  }<br>  <br>  return reversed;<br>} <br><br>// Example usage:<br>let inputString = &quot;hello&quot;;<br>let resultString = reverseString(inputString);<br>console.log(resultString); // Output: &quot;olleh&quot;</pre><h4>Explanation:</h4><ol><li><strong>Initialization</strong>: We start with an empty string reversed which will hold the final reversed string.</li><li><strong>Loop</strong>: We use a for loop that starts at the last character (str.length - 1) and moves towards the first character (i &gt;= 0).</li><li><strong>Concatenation</strong>: Inside the loop, each character is added to the reversed string.</li><li><strong>Return</strong>: After the loop completes, the fully reversed string is returned.</li></ol><h3>2. Reverse a Number using a Loop</h3><pre>function reverseNumber(num) {<br>  // Initialize the reversed number to 0<br>  let reversed = 0;<br>  <br>  // Loop until the number becomes 0<br>  while (num != 0) {<br>    // Get the last digit of the number<br>    let lastDigit = num % 10;<br>    <br>    // Update the reversed number by shifting the digits and adding the last digit<br>    reversed = reversed * 10 + lastDigit;<br>    <br>    // Remove the last digit from the number<br>    num = Math.floor(num / 10);<br>  }<br>  <br>  return reversed;<br>} <br><br>// Example usage:<br>let inputNumber = 12345;<br>let resultNumber = reverseNumber(inputNumber);<br>console.log(resultNumber); // Output: 54321</pre><h4>Explanation:</h4><ol><li><strong>Initialization</strong>: We start with reversed = 0, which will hold the reversed number.</li><li><strong>Loop</strong>: We use a while loop that continues as long as the number is not zero.</li><li><strong>Modulus Operation</strong>: Inside the loop, num % 10 gives the last digit of the number.</li><li><strong>Updating the Reversed Number</strong>: We multiply the current reversed number by 10 (to shift digits to the left) and then add the last digit.</li><li><strong>Removing the Last Digit</strong>: We use Math.floor(num / 10) to remove the last digit from the original number.</li><li><strong>Return</strong>: After the loop completes, the reversed number is returned.</li></ol><h3>3. Ascending and Descending Sort</h3><pre>// Bubble sort function for ascending order<br>function sortAscending(arr) {<br>  let n = arr.length;<br>  <br>  // Outer loop to traverse through the array<br>  for (let i = 0; i &lt; n; i++) {<br>    // Inner loop to compare adjacent elements<br>    for (let j = 0; j &lt; n - 1 - i; j++) {<br>      if (arr[j] &gt; arr[j + 1]) {<br>        // Swap if elements are in the wrong order<br>        let temp = arr[j];<br>        arr[j] = arr[j + 1];<br>        arr[j + 1] = temp;<br>      }<br>    }<br>  }<br>  <br>  return arr;<br>} <br><br>// Bubble sort function for descending order<br>function sortDescending(arr) {<br>  let n = arr.length;<br>  <br>  // Outer loop to traverse through the array<br>  for (let i = 0; i &lt; n; i++) {<br>    // Inner loop to compare adjacent elements<br>    for (let j = 0; j &lt; n - 1 - i; j++) {<br>      if (arr[j] &lt; arr[j + 1]) {<br>        // Swap if elements are in the wrong order<br>        let temp = arr[j];<br>        arr[j] = arr[j + 1];<br>        arr[j + 1] = temp;<br>      }<br>    }<br>  }<br>  <br>  return arr;<br>} <br><br>// Example usage<br>let numbers = [12, 3, 4, 15, 2, 6, 10, 2];<br>console.log(&quot;Original array: &quot;, numbers); <br><br>// Ascending order<br>let ascending = sortAscending([...numbers]); // Use spread operator to avoid modifying the original array<br>console.log(&quot;Ascending order: &quot;, ascending); <br><br>// Descending order<br>let descending = sortDescending([...numbers]); // Use spread operator to avoid modifying the original array<br>console.log(&quot;Descending order: &quot;, descending);</pre><h4>Explanation:</h4><ol><li><strong>Bubble Sort Algorithm</strong>: Both sorting functions use the bubble sort algorithm, which compares adjacent elements and swaps them if they are in the wrong order.</li><li><strong>Outer Loop</strong>: The outer loop runs through the array n times (where n is the array length). This ensures every element is compared with others.</li><li><strong>Inner Loop</strong>: The inner loop compares each pair of adjacent elements and swaps them if necessary.</li></ol><ul><li>For <strong>ascending</strong> order, we swap if the current element is greater than the next one.</li><li>For <strong>descending</strong> order, we swap if the current element is smaller than the next one.</li></ul><h4>Example Output:</h4><pre>Original array:  [12, 3, 4, 15, 2, 6, 10, 2]<br>Ascending order:  [2, 2, 3, 4, 6, 10, 12, 15]<br>Descending order:  [15, 12, 10, 6, 4, 3, 2, 2]</pre><h3>4. Print Non-Repeated Number</h3><pre>const numbers = [1, 1, 1, 2, 2, 2, 3, 3, 5, 6, 6, 6]; <br><br>console.log(&quot;Non-repeated numbers are:&quot;); <br>// Outer loop to iterate over each element in the array<br>for (let i = 0; i &lt; numbers.length; i++) {<br>    let count = 0; <br><br>    // Inner loop to count occurrences of the current number<br>    for (let j = 0; j &lt; numbers.length; j++) {<br>        if (numbers[i] === numbers[j]) {<br>            count++;<br>        }<br>    } <br><br>   // If the count is 1, print the number<br>    if (count === 1) {<br>        console.log(numbers[i]);<br>    }<br>} <br><br>// Output<br>Non-repeated numbers are:<br>5</pre><h3>Explanation:</h3><ol><li><strong>Input Array</strong>: The array contains the numbers [1,1,1,2,2,2,3,3,5,6,6]</li><li><strong>Outer Loop</strong>: We use an outer loop (for i=) to go through each element in the array.</li><li><strong>Inner Loop</strong>: For each number numbers[i], we have an inner loop (for j) that counts how many times the current number appears in the entire array by comparing numbers[i] with numbers[j].</li><li><strong>Condition Check</strong>: After counting the occurrences of the current number, we check if it only appears once (i.e., count === 1). If it does, we print the number.</li><li><strong>Result</strong>: The number 5 is the only one that appears exactly once, so it is printed as the non-repeated number.</li></ol><h3>How It Works:</h3><ul><li>The outer loop iterates over each element of the array, and for each element, the inner loop compares it with all other elements to count its occurrences.</li><li>The if condition checks if the count for a particular number is 1, and if so, it gets printed as a non-repeated number.</li></ul><h3>5. Print Most-Repeated Number</h3><pre>const numbers = [1, 1, 1, 2, 2, 2, 3, 3, 5, 6, 6, 6]; <br><br>// Create an object to store the frequency of each number<br>let numFrequency = {}; <br><br>// Populate the object with the frequency of each number<br>for (let number of numbers) {<br>    numFrequency[number] = (numFrequency[number] || 0) + 1;<br>} <br><br>// Variables to store the most repeating number and its frequency<br>let mostRepeatingNumber = -1;<br>let maxCount = 0; <br><br>// Find the number with the highest frequency<br>for (let number in numFrequency) {<br>    if (numFrequency[number] &gt; maxCount) {<br>        maxCount = numFrequency[number];<br>        mostRepeatingNumber = number;<br>    }<br>} <br><br>// Print the most repeating number and its frequency<br>console.log(`Most repeating number: ${mostRepeatingNumber} (repeats ${maxCount} times)`); <br><br><br>//Output:<br><br>Most repeating number: 1 (repeats 3 times)</pre><ol><li><strong>Input Array</strong>: We have the array [1, 1, 1, 2, 2, 2, 3, 3, 5, 6, 6, 6].</li><li><strong>Frequency Counting</strong>:</li></ol><ul><li>We create an object (numFrequency) to store the frequency of each number.</li><li>We iterate through the numbers array, and for each number, we update its frequency in the numFrequency object. If the number already exists in the object, we increment its count. If not, we set its count to 1.</li></ul><p><strong>3. Find the Most Repeating Number</strong>:</p><ul><li>We then loop through the numFrequency object to find the number with the highest frequency (maxCount).</li><li>Each time we find a number with a higher frequency, we update the mostRepeatingNumber and maxCount values.</li></ul><h3>6. Extract digit from given string</h3><p>To extract &quot;123&quot; from the string &quot;helloworld123&quot; in JavaScript, you can use a regular expression. Here&#39;s an example:</p><pre>let str = &quot;helloworld123&quot;;<br>let numbers = str.match(/\d+/)[0];  // \d+ matches one or more digits<br>console.log(numbers);  // Output: 123</pre><p>Explanation:</p><ul><li>\d+ is a regular expression pattern that matches one or more digits (\d means &quot;digit&quot;).</li><li>match() returns an array where the first element is the matched result.</li><li>[0] extracts the matched part of the string from the array.</li></ul><h3>7. Count the number of occurrences of each character in a string</h3><p>To count the number of occurrences of each character in a string like &quot;helloworld123&quot;, you can use an object to store the frequency of each character. Here&#39;s an example in JavaScript:</p><pre>let str = &quot;helloworld123&quot;;<br>let charCount = {}; <br><br>for (let char of str) {<br>  charCount[char] = charCount[char] ? charCount[char] + 1 : 1;<br>} <br><br>console.log(charCount);</pre><p>Output will be something like:</p><pre>{<br>  h: 1,<br>  e: 1,<br>  l: 3,<br>  o: 2,<br>  w: 1,<br>  r: 1,<br>  d: 1,<br>  1: 1,<br>  2: 1,<br>  3: 1<br>}</pre><h3>Explanation:</h3><ul><li>We loop through each character in the string.</li><li>For each character, we check if it already exists in the charCount object:</li><li>If it exists, we increment its value.</li><li>If it doesn’t exist, we initialize it with a value of 1.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7445bb41afde" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SonarQube-Scanner]]></title>
            <link>https://sudheer-baraker.medium.com/sonarqube-scanner-ba3a2b6cb678?source=rss-f17fb69241fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba3a2b6cb678</guid>
            <category><![CDATA[devops-practice]]></category>
            <category><![CDATA[jenkins]]></category>
            <category><![CDATA[jenkins-pipeline]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[devsecops]]></category>
            <dc:creator><![CDATA[Sudheer]]></dc:creator>
            <pubDate>Sat, 07 Oct 2023 18:42:20 GMT</pubDate>
            <atom:updated>2023-10-12T10:23:37.368Z</atom:updated>
            <content:encoded><![CDATA[<p>SonarQube is an open-source platform that provides static code analysis and code quality management. It is designed to help developers and development teams identify and fix code issues early in the software development lifecycle. SonarQube analyzes source code for bugs, vulnerabilities, code smells, and code duplications, and provides detailed reports with actionable insights.</p><p>Here are some key features of SonarQube:</p><ol><li><strong>Static Code Analysis:</strong> SonarQube performs static analysis on source code, analyzing its structure, syntax, and patterns to identify potential issues and violations of coding standards.</li><li><strong>Code Quality Metrics:</strong> SonarQube calculates various code quality metrics, such as code coverage, cyclomatic complexity, duplications, and maintainability index. These metrics help developers evaluate the <br> overall quality of their codebase.</li><li><strong>Issue Tracking: </strong>SonarQube identifies and categorizes issues in the code, such as bugs, security vulnerabilities, and code smells. It provides detailed information about each issue, including the affected <br> code snippet, severity level, and recommended fixes.</li><li><strong>Continuous Inspection: </strong>SonarQube supports continuous integration and continuous delivery (CI/CD) workflows by integrating with popular build tools and version control systems. It can be seamlessly integrated <br> into the development pipeline to automatically analyze code with every build.</li><li><strong>Custom Rules and Quality Profiles:</strong> SonarQube allows you to define custom coding rules and quality profiles to align with your project’s specific requirements and coding standards. This helps enforce <br> consistent code quality across your development team.</li><li><strong>Integrations: </strong>SonarQube integrates with a wide range of development tools and IDEs, enabling developers to receive real-time feedback on code quality while they write code. It also integrates with popular <br> CI/CD platforms to provide continuous inspection throughout the software development process.</li></ol><p>By using SonarQube, development teams can proactively identify and address code issues, improve code maintainability, enhance security, and ensure adherence to coding standards. It helps foster a culture of quality within development teams and promotes the delivery of robust and reliable software.</p><h3>Docker Installation</h3><p>sudo apt-get update<br>sudo apt-get install ca-certificates curl gnupg</p><p>sudo install -m 0755 -d /etc/apt/keyrings<br>curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg — dearmor -o /etc/apt/keyrings/docker.gpg<br>sudo chmod a+r /etc/apt/keyrings/docker.gpg</p><p>echo \<br> “deb [arch=”$(dpkg — print-architecture)” signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu \<br> “$(. /etc/os-release &amp;&amp; echo “$VERSION_CODENAME”)” stable” | \<br> sudo tee /etc/apt/sources.list.d/docker.list &gt; /dev/null</p><p>sudo apt-get update</p><p>sudo apt-get install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin</p><p>sudo apt install docker-compose</p><p>service docker restart<br>sudo usermod -aG docker $USER<br>newgrp docker<br>sudo chmod 666 /var/run/docker.sock<br>sudo systemctl restart docker</p><h4>TO ISNTALL SONARQUBE USING DOCKER RUN BELOW COMMAND</h4><blockquote>docker run -d — — name sonar -p 9000:9000 sonarqube:lts-community</blockquote><h3># Real World Scenario: Code Quality Assessment and Continuous Improvement</h3><p><strong>Background</strong><br>A software development team is working on a complex web application project with multiple developers contributing code. The team wants to ensure code quality and identify and address any code issues early in the development process. They decide to incorporate SonarQube into their workflow to achieve these goals.</p><p><strong>Steps</strong></p><p><strong>1.Integration with CI/CD Pipeline:</strong><br>The team integrates SonarQube into their CI/CD pipeline, ensuring that code analysis is performed automatically with every build. They configure their build tool to trigger SonarQube analysis after the code compilation step.</p><p><strong>2.Static Code Analysis:</strong><br>During each build, SonarQube performs static code analysis on the source code. It scans the codebase for bugs, vulnerabilities, code smells, and code duplications.</p><p><strong>3.Quality Reports and Dashboards:</strong><br>SonarQube generates detailed quality reports and provides a dashboard that highlights code issues, quality metrics, and trends over time. The team can easily access these reports to gain insights into the codebase’s overall quality and track improvements.</p><p><strong>4.Issue Management:</strong><br>SonarQube categorizes code issues by severity and provides detailed information about each issue. The team can prioritize and address critical issues promptly to prevent potential bugs and security vulnerabilities.</p><p><strong>5.Code Review and Collaboration:</strong><br>SonarQube facilitates code review and collaboration within the team. Developers can review the SonarQube reports, identify areas for improvement, and discuss solutions to address code issues.</p><p><strong>6.Enforcement of Coding Standards:</strong><br>SonarQube enforces coding standards by checking code against predefined rules and quality profiles. The team configures SonarQube to match their project’s specific requirements and coding standards, ensuring consistent code quality across the development team.</p><p><strong>7.Continuous Improvement:</strong><br>With SonarQube’s insights and reports, the team continuously improves the code quality. They identify recurring issues, refactor code, and apply best practices to prevent similar issues in the future.</p><p><strong>8.Monitoring Code Quality Trends:</strong><br>The team regularly monitors code quality trends using SonarQube’s reports and dashboards. They can identify improvements or regressions in code quality over time and take appropriate actions to maintain or enhance the overall quality.</p><p>By incorporating SonarQube into their development workflow, the team can proactively identify and address code issues, improve code maintainability, enhance security, and adhere to coding standards. SonarQube helps the team foster a culture of quality and continuous improvement, leading to the delivery of robust and reliable software.</p><p>To make sure code coverage works fine add below things in your pom file at respective places.</p><p><strong>Here’s the POM format with the added items for enabling code coverage with JaCoCo:</strong></p><p>&lt;project&gt;<br> &lt;! — Other project configuration →</p><p>&lt;properties&gt;<br> &lt;! — JaCoCo Properties →<br> &lt;jacoco.version&gt;0.8.6&lt;/jacoco.version&gt;<br> &lt;sonar.java.coveragePlugin&gt;jacoco&lt;/sonar.java.coveragePlugin&gt;<br> &lt;sonar.dynamicAnalysis&gt;reuseReports&lt;/sonar.dynamicAnalysis&gt;<br> &lt;sonar.jacoco.reportPath&gt;${project.basedir}/../target/jacoco.exec&lt;/sonar.jacoco.reportPath&gt;<br> &lt;sonar.language&gt;java&lt;/sonar.language&gt;<br> &lt;/properties&gt;</p><p>&lt;! — Other dependencies →</p><p>&lt;dependencies&gt;<br> &lt;! — Other dependencies →</p><p>&lt;dependency&gt;<br> &lt;groupId&gt;org.jacoco&lt;/groupId&gt;<br> &lt;artifactId&gt;jacoco-maven-plugin&lt;/artifactId&gt;<br> &lt;version&gt;0.8.6&lt;/version&gt;<br> &lt;/dependency&gt;</p><p>&lt;! — Other dependencies →<br> &lt;/dependencies&gt;</p><p>&lt;! — Other plugin configurations →</p><p>&lt;build&gt;<br> &lt;plugins&gt;<br> &lt;! — Other plugins →</p><p>&lt;plugin&gt;<br> &lt;groupId&gt;org.jacoco&lt;/groupId&gt;<br> &lt;artifactId&gt;jacoco-maven-plugin&lt;/artifactId&gt;<br> &lt;version&gt;${jacoco.version}&lt;/version&gt;<br> &lt;executions&gt;<br> &lt;execution&gt;<br> &lt;id&gt;jacoco-initialize&lt;/id&gt;<br> &lt;goals&gt;<br> &lt;goal&gt;prepare-agent&lt;/goal&gt;<br> &lt;/goals&gt;<br> &lt;/execution&gt;<br> &lt;execution&gt;<br> &lt;id&gt;jacoco-site&lt;/id&gt;<br> &lt;phase&gt;package&lt;/phase&gt;<br> &lt;goals&gt;<br> &lt;goal&gt;report&lt;/goal&gt;<br> &lt;/goals&gt;<br> &lt;/execution&gt;<br> &lt;/executions&gt;<br> &lt;/plugin&gt;</p><p>&lt;! — Other plugins →<br> &lt;/plugins&gt;<br> &lt;/build&gt;</p><p>&lt;! — Other project configuration →<br>&lt;/project&gt;</p><p>Make sure to include this code snippet within the &lt;project&gt; tags of your existing POM file, and adjust any other project-specific configurations as needed.</p><p><strong>Jenkins pipeline to run SOnar analysis</strong></p><p>pipeline {<br> agent any<br> <br> tools {<br> jdk ‘jdk11’<br> maven ‘maven3’<br> }<br> <br> environment {<br> SCANNER_HOME = tool ‘sonar-scanner’<br> }<br> <br> stages {<br> stage(‘Checkout’) {<br> steps {<br> # Checkout your Java project from version control<br> # For example:<br> # git ‘<a href="https://github.com/your-repo/java-project.git&#39;">https://github.com/your-repo/java-project.git’</a><br> }<br> }<br> <br> stage(‘Build’) {<br> steps {<br> # Build your Java project<br> # For example:<br> # sh ‘mvn clean install’<br> }<br> }<br> <br> stage(‘SonarQube Analysis’) {<br> steps {<br> # Run SonarQube analysis<br> # Make sure you have SonarQube configured in Jenkins and provide the correct SonarQube server credentials<br> <br> withSonarQubeEnv(‘sonar-server’) {<br> sh ‘’’ $SCANNER_HOME/bin/sonar-scanner -Dsonar.projectName=Petclinic \<br> -Dsonar.java.binaries=. \<br> -Dsonar.projectKey=Petclinic ‘’’<br> }<br> }<br> <br> stage(‘Deploy to Tomcat’) {<br> steps {<br> # Additional steps to deploy your Java project<br> Invoke-Expression “sudo cp target/*war apache-tomcat-path/webapps”<br> }<br> }<br> }<br>}<br>Once the pipeline is success you will get the results in sonarqube.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ADn4L2jZHq3Aaw-c.png" /></figure><p>===============================================================</p><p>The above information is up to my understanding. Suggestions are always welcome.</p><p>Thank you.</p><p>Sudheer Baraker</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba3a2b6cb678" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrate OWASP Dependency Check in Jenkins Pipeline]]></title>
            <link>https://sudheer-baraker.medium.com/integrate-owasp-dependency-check-in-jenkins-pipeline-748d8aefc2b7?source=rss-f17fb69241fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/748d8aefc2b7</guid>
            <category><![CDATA[jenkins-pipeline]]></category>
            <category><![CDATA[devsecops]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Sudheer]]></dc:creator>
            <pubDate>Sat, 07 Oct 2023 05:59:33 GMT</pubDate>
            <atom:updated>2023-10-07T18:53:05.050Z</atom:updated>
            <content:encoded><![CDATA[<h3>OWASP Dependency-Check</h3><blockquote>OWASP Dependency-Check is a tool that identifies project dependencies and checks if there are any known, publicly disclosed, vulnerabilities. It can be used in various software development contexts to enhance the security of applications by identifying and alerting developers about vulnerable components that may be included in their projects.</blockquote><h3>Here are some key points about OWASP Dependency-Check:</h3><ol><li><strong>Identification of Vulnerabilities:</strong> Dependency-Check uses a combination of public and private vulnerability databases to identify known vulnerabilities in project dependencies. It supports various programming languages and package managers.</li><li><strong>Integration with Build Tools:</strong> It can be integrated into the build process of a project, making it easier for developers to regularly check for vulnerabilities as part of their development workflow. Common build tools such as Maven, Gradle, Ant, and others are supported.</li><li><strong>Wide Language and Ecosystem Support: </strong>OWASP Dependency-Check supports multiple programming languages and ecosystems, including Java, .NET, Node.js, Ruby, Python, and more. This makes it versatile and applicable to a wide range of projects.</li><li><strong>Command-Line and CI/CD Integration: </strong>It can be used from the command line, making it suitable for use in continuous integration/continuous deployment (CI/CD) pipelines. This ensures that vulnerability checks are performed automatically as part of the development and deployment process.</li><li><strong>Report Generation:</strong> Dependency-Check can generate reports in various formats, including HTML, XML, JSON, and CSV. These reports provide detailed information about the identified vulnerabilities, allowing developers and security teams to take appropriate action.</li><li><strong>Active Community:</strong> Being an OWASP project, Dependency-Check benefits from an active and collaborative community. This means that updates, improvements, and new features are likely to be developed and shared by the community.</li><li><strong>Integration with Other Security Tools: </strong>It can be used in conjunction with other security tools to provide a comprehensive security analysis of a project.</li></ol><h3>Integrate OWASP Dependency Check In Jenkins Pipeline</h3><p>The first step is to go to the Jenkins dashboard, select<strong> <em>Manage Jenkins-&gt;Manage Plugins</em></strong> option, and install the <a href="https://plugins.jenkins.io/dependency-check-jenkins-plugin">OWASP Dependency-Check Plugin</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3DHR1AGetLoEXp2_bOg_nw.png" /></figure><p>Install Dependency-Check Plugin</p><p>The second step is to install the dependency-check tool from the Jenkins Global Tool Configuration under the System Configuration. In the Jenkins dashboard, select<strong> <em>Manage Jenkins-&gt;Global Tool Configuration </em></strong>option, and scroll down to the last you will find the Dependency Check Installation block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*qjtq_Ak6Shb0TyQR.png" /></figure><p>Click on<strong> Add Dependency Check </strong>and enter the name for the installation tool e.g. ( OWASP Dependency-Check Vulnerabilities ) make sure to give a relevant name.</p><p>Check the <strong>Install automatically</strong> box and select the <strong>Add Installer</strong> then click on the Dependency-check from the dropdown menu and select the version. Then, click on <strong>Apply &amp; Save.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*pXAmYgP3VFilAFLQ.png" /></figure><p>Dependency-Check Installer</p><p>After adding the OWASP Dependency-Check Plugin and Dependency-Check Installer in Jenkins. Edit your Jenkins Pipeline and add the below stage. Make sure the <strong>odcInstallation</strong> value should be the same as you have entered in the Jenkins Dependency-Check Installation in our case it is “OWASP Dependency-Check Vulnerabilities”.</p><p>Add the below stage to your Jenkins pipeline and then, start the build.</p><pre>stage(&#39;OWASP Dependency-Check Vulnerabilities&#39;) {<br>      steps {<br>        dependencyCheck additionalArguments: &#39;&#39;&#39; <br>                    -o &#39;./&#39;<br>                    -s &#39;./&#39;<br>                    -f &#39;ALL&#39; <br>                    --prettyPrint&#39;&#39;&#39;, odcInstallation: &#39;OWASP Dependency-Check Vulnerabilities&#39;<br>        <br>        dependencyCheckPublisher pattern: &#39;dependency-check-report.xml&#39;<br>      }<br>    }</pre><p>After the build got succeeded, go inside the build to check the Dependency-Check report and select the Dependency-Check on the left side menu you will see the HTML report on the console based on the severity level.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*0KT9kdVJEph2TMQQ.png" /></figure><p>Dependency-Check Results</p><p>Finally, we have successfully integrated the Dependency-Check tool into our Jenkins Pipeline.</p><p>===============================================================</p><p>The above information is up to my understanding. Suggestions are always welcome.</p><p>Thank you.</p><p>Sudheer Baraker</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=748d8aefc2b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jenkins CI/CD Pipeline to Deploy Java Application on Tomcat Server]]></title>
            <link>https://sudheer-baraker.medium.com/jenkins-ci-cd-pipeline-to-deploy-java-application-on-tomcat-server-97b92df2da38?source=rss-f17fb69241fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/97b92df2da38</guid>
            <category><![CDATA[jenkins-pipeline]]></category>
            <category><![CDATA[devops-practice]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Sudheer]]></dc:creator>
            <pubDate>Fri, 06 Oct 2023 06:22:38 GMT</pubDate>
            <atom:updated>2023-10-06T06:22:38.549Z</atom:updated>
            <content:encoded><![CDATA[<p>Use Jenkins to set up a CI/CD pipeline that will compile and test a Maven project and deploy it to a Tomcat Server.</p><p>Project description:</p><ol><li>The project aims to automate the building, testing and deployment process of web application using Jenkins, GitHub and Tomcat server.</li><li>The pipeline will include stages such as check out code from GitHub, building, archive artifact, deployment on tomcat server and send notification.</li></ol><p>Use the following:</p><ol><li><strong>Java</strong>: To create the website.</li><li><strong>Git</strong>: As a version control system for the program.</li><li><strong>Jenkins</strong>: To create the build pipeline.</li><li><strong>Maven</strong>: To compile the program.</li><li><strong>Tomcat</strong>: To host the website.</li><li><strong>AWS EC2</strong>: To run Tomcat.</li></ol><p><strong>Create AWS EC2 Instance.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BaxnKS4quAKErmkm3kky8w.png" /></figure><p><strong>Create Key-Pair</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*_HIj6C7BOstE2a0KWHe6EQ.png" /></figure><p><strong>EC2 Instance is launched successfully.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bePULC4VH9J6GSVFJPOEjQ.png" /></figure><p><strong>Connect to EC2 Instance</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UKNHwau-0d66m6W7NkEGFQ.png" /></figure><p><strong>Connected to EC2 Instance</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qTypnYOvTwwkqVx-mD4tFQ.png" /></figure><p><strong>Update the Instance.</strong></p><blockquote><strong>$ apt update</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RhzpwRnJRXjCN8YeWJAovw.png" /></figure><p><strong>Install Java JDK</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eFc560F_vk4CAK20kLMb9Q.png" /></figure><p><strong>Install Tomcat9 Server on EC2 instance.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WVK2gAZP6nvhuU2kFuwsDA.png" /></figure><p><strong>Open tomcat user to add the users.</strong></p><blockquote>$ vi tomcat-users.xml</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*vrIj8Y225xCmLJM1paM5rg.png" /></figure><p><strong>Add username, password and roles for the user under &lt;tomcat-user&gt;.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hNEX8wkdDAVQfN_6myFJdg.png" /></figure><p><strong>Restart the service.</strong></p><blockquote><strong>$ service tomcat9 restart</strong></blockquote><p><strong>To add port 8080 for an instance, you need to allow traffic on port 8080 in instance security group and configure the instance firewall to allow traffic on port 8080.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TKoAiOQPLJzREwR2HU1wwQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dfitpOwJy6YoK-ywYQqwDQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u73lioVqZVHsNT89vffewA.png" /></figure><p><strong>Now, Access the tomcat server with Public IP and Port 8080</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JpvNAzwkje_TQfs-V5rAkQ.png" /></figure><p><strong>Provide Username and password that we configured in tomcat-user.xml under &lt;tomcat-user&gt; tag.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sG8CGt9oVaYC5YYAa1_FxA.png" /></figure><p><strong>Successfully accessed Apache Tomcat server UI.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F5EQQ3y2okOcnKlco9WFIw.png" /></figure><p><strong>Create CI/CD pipeline to build and deploy the application on Tomcat server.</strong></p><p><strong>Create Pipeline project and give the name.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XvnRapHtw0L9C0NODOB9AA.png" /></figure><p><strong>Provide Git URL for the project and Select tomcat credentials to deploy the application.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QxZ3xDY7ffx9V2agvNP2lA.png" /></figure><p><strong>To add tomcat credentials, Click AddàProvide tomcat server credentials (Username and Password).</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-HIGbTh9dFnumShKYeYyyQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sCHejm34PD1ICDz28uWL-g.png" /></figure><p><strong>Pipeline code to build and deploy the application on tomcat server.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cskIjYSVz48uX0cud0AEHQ.png" /></figure><p><strong>CI/CD Pipeline job successfully built and deployed the application on the server.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wKuqRkGssxib4ZN2_5Ttbw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*WWkMpIQWGPw5iNdGunk00w.png" /></figure><p><strong>Java Application deployed on the server. Open the application.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RMpLAoF5LekVEh2Wik3_9Q.png" /></figure><p><strong>Java Application accessed using Public IP, Port Number: 8080 and Application URL.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JiFdpqJGnhy5UfcUBj5w8Q.png" /></figure><p>Thank you for reading.</p><p>Sudheer Baraker.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97b92df2da38" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>