
30/10/2024
Automating UI tests for form validation can significantly enhance the reliability of your application. In this tutorial, we’ll be using Selenium, a powerful tool for web automation, to validate a web form. Let’s get started!
Before we proceed, make sure you have the following:
pip install selenium
Assuming you have a sample web application with a form that includes:
Here’s how your basic form might look in HTML:
<form id="registrationForm"> <input type="text" id="email" placeholder="Email" required/> <input type="password" id="password" placeholder="Password" required/> <button type="submit">Register</button> </form>
Now, let’s write a Python script that uses Selenium to test this form validation.
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys import time # Set up the Chrome driver driver = webdriver.Chrome() # Open the webpage with form driver.get("http://example.com/registration") # Replace with your form URL # Locate the email and password fields email_field = driver.find_element(By.ID, "email") password_field = driver.find_element(By.ID, "password") submit_button = driver.find_element(By.CSS_SELECTOR, "button[type='submit']") # Function to test form validation with various scenarios def test_form_validation(): # Test empty fields submit_button.click() time.sleep(1) # Wait for validation feedback assert "This field is required." in driver.page_source # Modify with your error message # Test invalid email format email_field.send_keys("invalid-email") password_field.send_keys("validPassword123") submit_button.click() time.sleep(1) # Wait for validation feedback assert "Please enter a valid email address." in driver.page_source # Modify as needed # Test valid submission email_field.clear() password_field.clear() email_field.send_keys("test@example.com") password_field.send_keys("validPassword123") submit_button.click() time.sleep(1) # Wait for feedback assert "Registration successful!" in driver.page_source # Change as required # Execute the tests test_form_validation() # Close the driver driver.quit()
By using this script, you ensure that your form validation works as expected, catching errors in user input before data submission. Remember to adjust the assertions and messages based on your actual application’s behavior. Happy testing!
30/10/2024 | UI Manual Testing
30/10/2024 | UI Manual Testing