read 13 min
29 / 29
Feb 3

Day 6 of 100daysofcode : Testing Interactive Elements using Selenium

To test all the interactive elements on the DemoQA website using Selenium, we need to cover different types of elements such as:

  • Checkboxes
  • Radio Buttons
  • Text Inputs
  • Buttons
  • Links
  • Alerts
  • Sliders
  • Forms

Below is an example Selenium script that tests all major elements on the DemoQA website

from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import time # Initialize WebDriver (Chrome in this example) options = webdriver.ChromeOptions() options.add_argument('--start-maximized') driver = webdriver.Chrome(options=options) # Function to test all elements on the DemoQA website def test_demoqa_elements(): driver.get("https://demoqa.com/") # Wait for the page to load WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.TAG_NAME, "body"))) # Test Checkboxes print("Testing Checkboxes...") driver.find_element(By.XPATH, "//span[text()='Elements']").click() WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//span[text()='Checkbox']"))).click() checkbox1 = driver.find_element(By.CLASS_NAME, "rct-checkbox") checkbox1.click() time.sleep(1) print("Checkbox selected.") checkbox1.click() # Deselecting print("Checkbox deselected.") # Test Radio Buttons print("Testing Radio Buttons...") driver.find_element(By.XPATH, "//span[text()='Radio Button']").click() WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//label[text()='Yes']"))).click() time.sleep(1) print("Radio Button 'Yes' selected.") # Test Text Inputs print("Testing Text Inputs...") driver.find_element(By.XPATH, "//span[text()='Text Box']").click() WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "userName"))).send_keys("John Doe") driver.find_element(By.ID, "userEmail").send_keys("john.doe@example.com") driver.find_element(By.ID, "currentAddress").send_keys("123 Main St.") driver.find_element(By.ID, "permanentAddress").send_keys("456 Oak St.") driver.find_element(By.XPATH, "//button[text()='Submit']").click() time.sleep(1) print("Text box form submitted.") # Test Buttons print("Testing Buttons...") driver.find_element(By.XPATH, "//span[text()='Buttons']").click() WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "doubleClickBtn"))).click() time.sleep(1) print("Button clicked.") # Test Links print("Testing Links...") driver.find_element(By.XPATH, "//span[text()='Links']").click() WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//a[text()='Home']"))).click() print("Navigated to 'Home' link.") time.sleep(2) # Test Alerts print("Testing Alerts...") driver.find_element(By.XPATH, "//span[text()='Alerts, Frame & Windows']").click() driver.find_element(By.ID, "alertButton").click() WebDriverWait(driver, 10).until(EC.alert_is_present()) driver.switch_to.alert.accept() # Accept the alert print("Alert accepted.") # Test Sliders print("Testing Sliders...") driver.find_element(By.XPATH, "//span[text()='Slider']").click() slider = driver.find_element(By.XPATH, "//input[@type='range']") ActionChains(driver).drag_and_drop_by_offset(slider, 50, 0).perform() # Move slider time.sleep(1) print("Slider value changed.") # Test Modal Dialog print("Testing Modal Dialog...") driver.find_element(By.XPATH, "//span[text()='Modal Dialogs']").click() driver.find_element(By.ID, "showSmallModal").click() # Open small modal WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "closeSmallModal"))).click() # Close modal print("Modal dialog tested.") # Test Accordions print("Testing Accordions...") driver.find_element(By.XPATH, "//span[text()='Accordions']").click() driver.find_element(By.XPATH, "//button[text()='First Button']").click() # Expand first section time.sleep(1) print("Accordion section expanded.") # Run the test function try: test_demoqa_elements() finally: driver.quit()

Day 7: Find The Bug

from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys import time # Set up the WebDriver driver = webdriver.Chrome() try: # Open the website driver.get("https://the-internet.herokuapp.com/login") # Locate the username field and enter text username_field = driver.find_element(By.ID, "username") username_field.send_keys("tomsmith") # Correct username # Locate the password field and enter text password_field = driver.find_element(By.ID, "password") password_field.send_keys("SuperSecretPassword!") # Correct password # Click the login button login_button = driver.find_element(By.XPATH, "//button[@type='submit']") login_button.click() # Wait for a short while to allow the page to load time.sleep(3) # Verify if the login was successful by checking for a specific element success_message = driver.find_element(By.XPATH, "//div[@class='flash success']") assert "You logged into a secure area!" in success_message.text print("Test Passed: Login successful!") #Click the logout button logout_button = driver.find_element(By.CLASS_NAME, "icon-2x icon-signout") logout_button.click() except AssertionError as e: print("Test Failed: Assertion error -", e) except Exception as e: print("Test Failed: An error occurred -", e) finally: # Close the browser driver.quit()

Day 8 of 100daysofcode : Essential Selenium skills every QA Engineer must know :point_down:

𝟭. 𝗖𝗼𝗿𝗲 𝗖𝗼𝗻𝗰𝗲𝗽𝘁𝘀
Open-source web automation framework.
Components: WebDriver, IDE, Grid.

𝟮. 𝗦𝗲𝘁𝘂𝗽
Install required language (Java, Python).
Configure IDE and WebDriver.

𝟯. 𝗣𝗿𝗼𝗴𝗿𝗮𝗺𝗺𝗶𝗻𝗴 𝗞𝗻𝗼𝘄𝗹𝗲𝗱𝗴𝗲
Proficiency in Java, Python, C#, etc.

𝟰. 𝗟𝗼𝗰𝗮𝘁𝗼𝗿𝘀
Identify web elements: ID, CSS, XPath, etc.

𝟱. 𝗪𝗲𝗯𝗗𝗿𝗶𝘃𝗲𝗿 𝗕𝗮𝘀𝗶𝗰𝘀
Browser actions: Click, Send Keys, Navigation.
Handle iframes, alerts, and pop-ups.

𝟲. 𝗔𝗱𝘃𝗮𝗻𝗰𝗲𝗱 𝗧𝗲𝗰𝗵𝗻𝗶𝗾𝘂𝗲𝘀
Waits (Implicit, Explicit, Fluent).
Switch windows, manage cookies, take screenshots.

𝟳. 𝗧𝗲𝘀𝘁 𝗙𝗿𝗮𝗺𝗲𝘄𝗼𝗿𝗸𝘀
Integrate with JUnit, TestNG, or PyTest.
Data-driven testing and test suites.

𝟴. 𝗣𝗮𝗿𝗮𝗹𝗹𝗲𝗹 𝗧𝗲𝘀𝘁𝗶𝗻𝗴
Use Selenium Grid for distributed execution.

𝟵. 𝗕𝗲𝘀𝘁 𝗣𝗿𝗮𝗰𝘁𝗶𝗰𝗲𝘀
Reusable scripts, Page Object Model (POM).

𝟭𝟬. 𝗖𝗜/𝗖𝗗 𝗜𝗻𝘁𝗲𝗴𝗿𝗮𝘁𝗶𝗼𝗻
Use Jenkins, GitHub Actions, etc., for automation pipelines.

𝟭𝟭. 𝗥𝗲𝗽𝗼𝗿𝘁𝗶𝗻𝗴

  • Tools: Extent, Allure.
  • Logging: Log4j, Python logging.

𝟭𝟮. 𝗗𝘆𝗻𝗮𝗺𝗶𝗰 𝗖𝗼𝗻𝘁𝗲𝗻𝘁

  • Sync with dynamic elements, use JavaScript Executor.

𝟭𝟯. 𝗗𝗲𝗯𝘂𝗴𝗴𝗶𝗻𝗴

  • IDE tools, browser developer tools, handle exceptions.

𝟭𝟰. 𝗢𝗽𝘁𝗶𝗺𝗶𝘇𝗮𝘁𝗶𝗼𝗻

  • Avoid Thread.sleep(), optimize waits and locators.

𝟭𝟱. 𝗔𝗣𝗜 𝗧𝗲𝘀𝘁𝗶𝗻𝗴

  • Combine Selenium with Postman or RestAssured.

100daysofcode lebanon-mug

Day 9 of 100daysofcode : Top Challenges QA Engineers Face with Selenium—and How to Overcome Them

𝟭. 𝗦𝘁𝗲𝗲𝗽 𝗟𝗲𝗮𝗿𝗻𝗶𝗻𝗴 𝗖𝘂𝗿𝘃𝗲

𝗖𝗵𝗮𝗹𝗹𝗲𝗻𝗴𝗲: Beginners may find it difficult to grasp Selenium due to its reliance on programming languages like Java, Python, or C#.
𝗦𝗼𝗹𝘂𝘁𝗶𝗼𝗻: Focus on learning the basics of the programming language first and gradually build Selenium skills.

𝟮. 𝗛𝗮𝗻𝗱𝗹𝗶𝗻𝗴 𝗗𝘆𝗻𝗮𝗺𝗶𝗰 𝗘𝗹𝗲𝗺𝗲𝗻𝘁𝘀

𝗖𝗵𝗮𝗹𝗹𝗲𝗻𝗴𝗲: Many modern web applications use dynamic IDs or elements that change with each session, making it hard to locate elements reliably.
𝗦𝗼𝗹𝘂𝘁𝗶𝗼𝗻: Use robust locators like XPath, CSS selectors, or unique attributes.

𝟯. 𝗖𝗿𝗼𝘀𝘀-𝗕𝗿𝗼𝘄𝘀𝗲𝗿 𝗧𝗲𝘀𝘁𝗶𝗻𝗴

𝗖𝗵𝗮𝗹𝗹𝗲𝗻𝗴𝗲: Ensuring compatibility across different browsers can lead to inconsistencies due to varying browser implementations.
𝗦𝗼𝗹𝘂𝘁𝗶𝗼𝗻: Use the WebDriver API and run extensive testing across all required browsers.

𝟰. 𝗗𝗲𝗯𝘂𝗴𝗴𝗶𝗻𝗴 𝗮𝗻𝗱 𝗧𝗲𝘀𝘁 𝗙𝗹𝗮𝗸𝗶𝗻𝗲𝘀𝘀

𝗖𝗵𝗮𝗹𝗹𝗲𝗻𝗴𝗲: Tests can fail intermittently due to issues like timing, network latency, or improper waits.
𝗦𝗼𝗹𝘂𝘁𝗶𝗼𝗻: Implement explicit or fluent waits instead of implicit waits and ensure proper synchronization.

𝟱. 𝗜𝗻𝘁𝗲𝗴𝗿𝗮𝘁𝗶𝗼𝗻 𝘄𝗶𝘁𝗵 𝗢𝘁𝗵𝗲𝗿 𝗧𝗼𝗼𝗹𝘀

𝗖𝗵𝗮𝗹𝗹𝗲𝗻𝗴𝗲: Integrating Selenium with CI/CD pipelines, reporting tools, or test management platforms can be complex.
𝗦𝗼𝗹𝘂𝘁𝗶𝗼𝗻: Use frameworks like TestNG, JUnit, or integrations with Jenkins, GitHub Actions, or other tools.

𝟲. 𝗟𝗶𝗺𝗶𝘁𝗲𝗱 𝗦𝘂𝗽𝗽𝗼𝗿𝘁 𝗳𝗼𝗿 𝗖𝗮𝗽𝘁𝗰𝗵𝗮𝘀 𝗮𝗻𝗱 𝗧𝘄𝗼-𝗙𝗮𝗰𝘁𝗼𝗿 𝗔𝘂𝘁𝗵𝗲𝗻𝘁𝗶𝗰𝗮𝘁𝗶𝗼𝗻

𝗖𝗵𝗮𝗹𝗹𝗲𝗻𝗴𝗲: Automating tests involving captchas or 2FA is not straightforward.
𝗦𝗼𝗹𝘂𝘁𝗶𝗼𝗻: Use test environments with disabled captchas or simulate user behavior with backend support.

𝟳. 𝗛𝗮𝗻𝗱𝗹𝗶𝗻𝗴 𝗣𝗼𝗽-𝗨𝗽𝘀 𝗮𝗻𝗱 𝗔𝗹𝗲𝗿𝘁𝘀

𝗖𝗵𝗮𝗹𝗹𝗲𝗻𝗴𝗲: Pop-ups, alerts, or authentication windows may not be handled seamlessly by Selenium.
𝗦𝗼𝗹𝘂𝘁𝗶𝗼𝗻: Use Selenium’s switchTo() methods or consider custom scripts for better handling.

𝟴. 𝗧𝗲𝘀𝘁𝗶𝗻𝗴 𝗠𝗼𝗯𝗶𝗹𝗲 𝗔𝗽𝗽𝗹𝗶𝗰𝗮𝘁𝗶𝗼𝗻𝘀

𝗖𝗵𝗮𝗹𝗹𝗲𝗻𝗴𝗲: Selenium does not natively support mobile testing; you need tools like Appium for mobile platforms.
𝗦𝗼𝗹𝘂𝘁𝗶𝗼𝗻: Integrate Selenium with Appium or use other mobile testing tools.

𝟵. 𝗟𝗮𝗰𝗸 𝗼𝗳 𝗕𝘂𝗶𝗹𝘁-𝗶𝗻 𝗥𝗲𝗽𝗼𝗿𝘁𝗶𝗻𝗴

𝗖𝗵𝗮𝗹𝗹𝗲𝗻𝗴𝗲: Selenium does not provide detailed reporting features.
𝗦𝗼𝗹𝘂𝘁𝗶𝗼𝗻: Use third-party libraries or frameworks such as Extent Reports, Allure, or TestNG reports.

𝟭𝟬. 𝗠𝗮𝗶𝗻𝘁𝗮𝗶𝗻𝗶𝗻𝗴 𝗧𝗲𝘀𝘁 𝗦𝗰𝗿𝗶𝗽𝘁𝘀

𝗖𝗵𝗮𝗹𝗹𝗲𝗻𝗴𝗲: As applications evolve, maintaining Selenium test scripts becomes time-consuming.
𝗦𝗼𝗹𝘂𝘁𝗶𝗼𝗻: Follow modular frameworks, use Page Object Model (POM), and keep scripts well-documented.

𝟭𝟭. 𝗣𝗲𝗿𝗳𝗼𝗿𝗺𝗮𝗻𝗰𝗲 𝗮𝗻𝗱 𝗦𝗰𝗮𝗹𝗮𝗯𝗶𝗹𝗶𝘁𝘆 𝗜𝘀𝘀𝘂𝗲𝘀

𝗖𝗵𝗮𝗹𝗹𝗲𝗻𝗴𝗲: Running extensive test suites can be time-consuming and resource-intensive.
𝗦𝗼𝗹𝘂𝘁𝗶𝗼𝗻: Use grid-based execution like Selenium Grid or cloud-based solutions like BrowserStack or Sauce Labs.

100daysofcode lebanon-mug

Day 10: Introduction to Cypress: A Modern End-to-End Testing Framework

Cypress is a modern, open-source JavaScript-based testing framework designed for end-to-end testing of web applications.
It provides a fast, reliable, and easy-to-use environment for writing, debugging, and running tests directly in the browser. Developers use Cypress to verify user flows, UI components, and application functionality across different browsers, ensuring a seamless user experience.


100daysofcode lebanon-mug

Day 11:### 10 Things You Need to Know About Using Cypress in Testing :rocket:

  1. Built for Modern Web: Cypress thrives on real-time reloading for dynamic apps.
  2. Fast and Flawless Debugging: Time-travel your tests with snapshots of every step.
  3. No Selenium Here: It’s an independent powerhouse, running directly in the browser.
  4. Built-in Waiting: Forget sleep(). Cypress automatically waits for elements.
  5. Rich Error Messages: It doesn’t just fail—it tells you why with detailed logs.
  6. All-in-One: Test runner, assertions, and stubbing, all in one tool.
  7. JavaScript Rules: Your tests are written in JavaScript for maximum flexibility.
  8. Mocks Made Easy: Seamlessly stub or mock APIs to control test environments.
  9. Cross-Browser Testing: From Chrome to Firefox, Cypress has your back.
  10. Perfect for CI/CD: Integrate easily with Jenkins, CircleCI, and others.

Day 12 of 100daysofcode : Top 5 scenarios where Cypress is most effective

1. End-to-End Testing

  • Cypress is primarily designed for E2E testing of web applications. Use it to test the complete workflow of an application, from the user interface to backend interactions.
  • Example: Testing a login process, form submission, or multi-step checkout process.

2. UI/UX Testing

  • Cypress excels at testing the user interface and ensuring elements are displayed correctly and behave as expected.
  • Example: Verifying that buttons, menus, modals, and animations work as intended.

3. Integration Testing

  • It is suitable for testing how different parts of your application interact with each other, especially in single-page applications.
  • Example: Checking that API responses update the UI as expected or that dependent components render correctly.

4. Cross-Browser Testing

  • Cypress supports multiple browsers like Chrome, Edge, and Firefox, making it a good choice for cross-browser compatibility testing.
  • Example: Ensuring that the application behaves consistently across supported browsers.

5. Continuous Integration/Delivery Pipelines

Day 13 of 100daysofcode : Here are 10 tips and tricks to effectively use Cypress for automation testing:

1. Use Custom Commands

  • Simplify repetitive tasks by defining custom commands in the cypress/support/commands.js file.
  • Example:
    Cypress.Commands.add('login', (username, password) => { cy.visit('/login'); cy.get('#username').type(username); cy.get('#password').type(password); cy.get('#submit').click(); });
  • This keeps your test cases clean and reusable.

2. Leverage Cypress Fixtures

  • Use the fixtures folder to store reusable test data in JSON files.
  • Example:
    cy.fixture('user').then((user) => { cy.get('#username').type(user.username); cy.get('#password').type(user.password); });

3. Take Advantage of Assertions

  • Cypress has built-in assertions that simplify verifying UI elements.
  • Example:
    cy.get('.alert').should('be.visible').and('contain', 'Success');

4. Use Cypress Selectors Carefully

  • Use data-* attributes for stable selectors instead of classes or IDs that may change.
  • Example:
    <button data-cy="submit-btn">Submit</button>
    cy.get('[data-cy=submit-btn]').click();

5. Handle Network Requests with cy.intercept

  • Mock API requests and responses to test edge cases or scenarios.
  • Example:
    cy.intercept('GET', '/api/users', { fixture: 'users.json' }).as('getUsers'); cy.visit('/users'); cy.wait('@getUsers');

6. Utilize Cypress Plugins

  • Extend functionality using Cypress plugins like cypress-axe for accessibility testing or cypress-file-upload for file uploads.
  • Example with cypress-file-upload:
    cy.get('input[type="file"]').attachFile('file-to-upload.pdf');

7. Use .then() for Synchronous Commands

  • Chain asynchronous Cypress commands for cleaner test flows.
  • Example:
    cy.get('#price').invoke('text').then((priceText) => { const price = parseFloat(priceText); expect(price).to.be.greaterThan(0); });

8. Take Screenshots and Videos

  • Use cy.screenshot() for debugging or visual regression testing.
  • Enable video recording in the cypress.config.js file for CI/CD environments.

9. Parallelize Tests for Speed

  • Leverage Cypress Dashboard to split test execution across multiple machines or threads.
  • Example: Use the --parallel flag:
    npx cypress run --record --parallel

10. Debugging with Cypress

  • Use cy.pause() to pause tests at specific steps.
  • Use .debug() to inspect elements in the browser.
  • Leverage the built-in Cypress debugger with the browser’s Developer Tools.

By incorporating these tips into your Cypress workflow, you can write more efficient, maintainable, and robust automated tests.

lebanon-mug

Day 14 of 100daysofcode : Cypress Setup

Setting up Cypress for automation testing is straightforward and involves a few steps. Below is a detailed guide:


Step 1: Install Node.js

Cypress requires Node.js to run. If you don’t have Node.js installed:

  1. Download it from Node.js official website.
  2. Install it by following the prompts.

Step 2: Create a Project Directory

  1. Open your terminal or command prompt.
  2. Create a new project folder for your automation tests:
    mkdir cypress-automation cd cypress-automation
  3. Initialize a new Node.js project:
    npm init -y
    This creates a package.json file to manage your project dependencies.

Step 3: Install Cypress

Run the following command to install Cypress:

npm install cypress --save-dev

This will add Cypress as a development dependency in your project.


Step 4: Open Cypress

After installation, you can open Cypress using the following command:

npx cypress open

This command will:

  • Launch the Cypress Test Runner.
  • Create a default folder structure (cypress/) in your project directory:
    • cypress/e2e: Place your test files here.
    • cypress/fixtures: Store static data (e.g., JSON files) for your tests.
    • cypress/support: Add custom commands or reusable logic here.

Step 5: Write Your First Test

  1. Inside the cypress/e2e folder, create a new test file, for example:
    touch cypress/e2e/sample_test.cy.js
  2. Add a simple test in the file:
    describe('My First Test', () => { it('Visits the Cypress website', () => { cy.visit('https://www.cypress.io'); cy.contains('Features').click(); cy.url().should('include', '/features'); }); });

Step 6: Run Tests

  1. Start Cypress Test Runner:
    npx cypress open
  2. Select the test file you created (sample_test.cy.js) and run it.

Step 7: Configure Cypress (Optional)

You can customize Cypress settings in the cypress.config.js or cypress.config.ts file created in your project root. For example, to set a base URL for your tests:

const { defineConfig } = require('cypress'); module.exports = defineConfig({ e2e: { baseUrl: 'https://example.com', setupNodeEvents(on, config) { // implement node event listeners here }, }, });

Step 8: Add Cypress to Scripts (Optional)

To make running tests easier, add Cypress commands to your package.json scripts:

"scripts": { "cypress:open": "cypress open", "cypress:run": "cypress run" }

Now, you can run Cypress with:

  • npm run cypress:open: Opens the Test Runner.
  • npm run cypress:run: Runs tests in headless mode.

Step 9: Integrate Cypress with CI/CD (Optional)

To run Cypress tests in CI/CD pipelines, you can use the cypress run command. Add this step to your CI/CD configuration file (e.g., GitHub Actions, Jenkins, or CircleCI).


Step 10: Explore More Features

  • Assertions: Use Chai.js assertions built into Cypress.
  • Fixtures: Load external test data using cy.fixture().
  • Custom Commands: Add reusable logic in cypress/support/commands.js.

For more details, visit the Cypress Documentation.

lebanon-mug

Day 15 of 100daysofcode : Cypress Test for Login Functionality

describe('Login Page Test', () => { it('should allow a user to log in successfully', () => { // Visit the login page cy.visit('https://example.com/login'); // Enter username and password cy.get('input[name="username"]').type('testuser'); cy.get('input[name="password"]').type('Password123'); // Click the login button cy.get('button[type="submit"]').click(); // Assert the user is redirected to the dashboard cy.url().should('include', '/dashboard'); // Assert the welcome message is displayed cy.contains('Welcome, Test User!').should('be.visible'); }); });

Key Points:

  1. cy.visit(): Navigates to the specified URL.
  2. cy.get(): Finds elements using CSS selectors.
  3. type(): Types text into an input field.
  4. click(): Clicks on a button or element.
  5. Assertions:
    • should('include') verifies the URL.
    • should('be.visible') confirms an element is visible.

This example assumes that the login page contains inputs with the names username and password and a button with type="submit". You can adapt the selectors and assertions based on your application.

lebanon-mug

Day 16 of 100daysofcode : Testing Websites using Cypress

describe(‘Login Automation Test’, () => {
const baseUrl = ‘https://the-internet.herokuapp.com’;

beforeEach(() => {
// Visit the base URL before each test
cy.visit(${baseUrl}/login);
});

it(‘should login successfully with valid credentials’, () => {
cy.get(‘#username’).type(‘tomsmith’); // Enter valid username
cy.get(‘#password’).type(‘SuperSecretPassword!’); // Enter valid password
cy.get(‘button[type=“submit”]’).click(); // Click the Login button

// Assert successful login cy.get('.flash.success').should('contain.text', 'You logged into a secure area!');

});

it(‘should show error for invalid credentials’, () => {
cy.get(‘#username’).type(‘invalidUser’); // Enter invalid username
cy.get(‘#password’).type(‘invalidPassword’); // Enter invalid password
cy.get(‘button[type=“submit”]’).click(); // Click the Login button

// Assert error message cy.get('.flash.error').should('contain.text', 'Your username is invalid!');

});
});
lebanon-mug

Day 17 of 100daysofcode : Cypress Test Code for Wikipedia Search Functionality

describe('Wikipedia Search Functionality Test', () => { before(() => { // Visit Wikipedia homepage before the tests cy.visit('https://www.wikipedia.org'); }); it('should display the search input and language selector', () => { // Check if the search input is visible cy.get('input#searchInput').should('be.visible'); // Check if the language selector dropdown is visible cy.get('select#searchLanguage').should('be.visible'); }); it('should successfully perform a search and display

Day 18 of 100daysofcode : Advanced Automation using Cypress

Here’s an advanced automation testing script using Cypress. The script tests key functionalities of a sample e-commerce website, such as logging in, searching for a product, adding it to the cart, and completing a checkout process.

Prerequisites

Ensure you have Cypress installed and set up. Run the following in your project folder:

npm install cypress --save-dev

Cypress Script

// cypress/e2e/ecommerce_advanced_test.cy.js describe('E-Commerce Website - Advanced Automation Test', () => { const baseUrl = 'https://example-ecommerce.com'; // Replace with the actual website URL before(() => { cy.visit(baseUrl); // Navigate to the website }); it('Logs in successfully', () => { cy.get('a[href="/login"]').click(); // Click on the Login link cy.get('input[name="email"]').type('testuser@example.com'); // Enter email cy.get('input[name="password"]').type('TestPassword123!'); // Enter password cy.get('button[type="submit"]').click(); // Submit login form // Assert successful login cy.get('.user-profile').should('contain', 'Welcome, Test User'); }); it('Searches for a product and adds it to the cart', () => { cy.get('input[placeholder="Search"]').type('Wireless Mouse{enter}'); // Search for a product cy.get('.product-list').should('contain', 'Wireless Mouse'); // Assert product appears // Select the product cy.get('.product-card').contains('Wireless Mouse').click(); // Add the product to the cart cy.get('button').contains('Add to Cart').click(); // Assert product is added to the cart cy.get('.cart-notification').should('contain', 'Wireless Mouse added to your cart'); }); it('Completes the checkout process', () => { cy.get('.cart-icon').click(); // Open the cart cy.get('button').contains('Proceed to Checkout').click(); // Proceed to checkout // Fill in shipping information cy.get('input[name="address"]').type('123 Cypress St, Test City, TX'); cy.get('input[name="zip"]').type('12345'); cy.get('input[name="phone"]').type('1234567890'); // Choose payment method and complete the payment cy.get('input[name="payment"][value="credit-card"]').check(); cy.get('input[name="card-number"]').type('4111111111111111'); cy.get('input[name="expiry"]').type('12/25'); cy.get('input[name="cvv"]').type('123'); cy.get('button').contains('Place Order').click(); // Assert order completion cy.get('.order-confirmation').should('contain', 'Thank you for your order'); }); after(() => { // Log out after tests cy.get('.user-menu').click(); cy.get('a').contains('Logout').click(); // Assert successful logout cy.get('a[href="/login"]').should('be.visible'); }); });

Key Features of the Script:

  1. Modularized Tests: Each test case handles a specific functionality, making the script easier to debug and maintain.
  2. Dynamic Selectors: Uses robust and descriptive selectors to ensure test stability.
  3. Assertions: Verifies that each step is successful with should() assertions.
  4. Reusable Code: Leverages Cypress commands like cy.get() and chaining for efficiency.
  5. Complete Flow: Covers login, search, cart, checkout, and logout processes.

Run the Test

To execute the test, run the following command:

npx cypress open

From the Cypress Test Runner, select the ecommerce_advanced_test.cy.js file to run the test.
lebanon-mug

Day 19 of 100daysofcode : Playwright - For cross-browser end-to-end testing

Playwright is an excellent tool for cross-browser end-to-end testing. Developed by Microsoft, it provides fast and reliable automation for testing web applications across modern browsers. Here’s an overview of what makes Playwright stand out:

Key Features of Playwright

  1. Cross-Browser Support:
  • Works seamlessly with Chromium (Google Chrome, Microsoft Edge), WebKit (Safari), and Firefox.
  • Ensures your application is functional across all major browsers.
  1. Headless and Headed Modes:
  • Tests can be run in headless mode for faster execution or in headed mode for debugging.
  1. Automated Browser Contexts:
  • Playwright allows you to create isolated browser contexts for parallel execution of tests, saving time.
  1. Powerful API:
  • Provides robust APIs to simulate user interactions like clicking, typing, hovering, file uploads, and more.
  1. Built-In Test Runner:
  • Playwright Test includes a test runner with built-in features like parallel test execution, retries, fixtures, and more.
  1. Cross-Platform:
  • Playwright supports Linux, macOS, and Windows, ensuring compatibility across development environments.
  1. Network Interception:
  • Allows mocking API responses, testing different scenarios without requiring backend changes.
  1. Visual Comparisons:
  • Supports screenshot comparisons for visual regression testing.
  1. Language Support:
  • Playwright works with multiple languages like JavaScript/TypeScript, Python, Java, and C#.
  1. Debugging Tools:
  • Comes with Playwright Inspector to debug tests visually and trace logs for easier troubleshooting.

Why Choose Playwright?

  • Reliable and Fast: Auto-waits for elements and browser states, reducing flaky tests.
  • Open Source: Free to use with an active community.
  • Full Stack Testing: Covers both frontend and backend testing (e.g., API testing).
  • Mobile Emulation: Emulate devices for responsive testing.

playwright

Day 21 of 100daysofcode : Logging in using Playwright

const { chromium } = require('playwright'); (async () => { const browser = await chromium.launch({ headless: false }); const context = await browser.newContext(); const page = await context.newPage(); await page.goto('https://example.com/login'); // Replace with actual selectors and credentials await page.fill('#username', 'your_username'); await page.fill('#password', 'your_password'); await page.click('#login-button'); await page.waitForNavigation(); console.log('Login successful!'); await browser.close(); })();

lebanon-mug

Day 22 of 100daysofcode : advantages of using Playwright :

Here are the key advantages of using Playwright for automation testing:

1. Cross-Browser Support

  • Supports Chromium, Firefox, and WebKit.
  • Ensures consistent testing across different browsers.

2. Multi-Platform & Multi-Language

  • Works on Windows, macOS, and Linux.
  • Supports multiple languages: JavaScript, TypeScript, Python, Java, and C#.

3. Headless & Headed Execution

  • Can run tests in headless mode for faster execution.
  • Supports headed mode for debugging.

4. Auto-Wait & Smart Assertions

  • Automatically waits for elements to be ready before performing actions.
  • Provides robust assertions for reliable tests.

5. Parallel & Distributed Testing

  • Supports parallel execution to speed up test runs.
  • Integrates with CI/CD pipelines for efficient testing.

6. Mobile Emulation & Device Testing

  • Simulates different mobile devices and screen sizes.
  • Supports geolocation, permissions, and network throttling.

7. Network Interception & Request Mocking

  • Allows modifying network requests and responses.
  • Helps in testing API calls and simulating different network conditions.

8. Visual & Screenshot Testing

  • Supports screenshot and video recording.
  • Enables visual regression testing.

9. Built-in Test Generator

  • Comes with a CodeGen tool to generate test scripts automatically.

10. Strong Community & Active Development

  • Backed by Microsoft, ensuring regular updates and improvements.
  • Growing community support and documentation.

Day 23 of 100daysofcode : Cross-Browser Testing Script using Playwright

const { chromium, firefox, webkit } = require('playwright'); (async () => { // Browsers to test const browsers = [ { name: 'Chromium', instance: chromium }, { name: 'Firefox', instance: firefox }, { name: 'Webkit', instance: webkit }, ]; // URL to test const url = 'https://example.com'; for (const browserType of browsers) { const browser = await browserType.instance.launch({ headless: false }); const context = await browser.newContext(); const page = await context.newPage(); console.log(`\nTesting on ${browserType.name}`); try { // Navigate to the page await page.goto(url); console.log(`Navigated to ${url}`); // Example assertions const pageTitle = await page.title(); console.log(`Page Title: ${pageTitle}`); // Check for an element (adjust selector as needed) const element = await page.$('h1'); if (element) { console.log('Header found successfully.'); } else { console.log('Header NOT found!'); } // Simulate interaction await page.click('a'); // Click on the first link await page.waitForTimeout(2000); // Wait for navigation console.log('Interaction successful.'); } catch (error) { console.error(`Error testing on ${browserType.name}:`, error); } finally { await browser.close(); } } })();

This topic will automatically close in 3 months.