Skip to content
This repository was archived by the owner on Feb 9, 2026. It is now read-only.

Selenium Quick Start Guide

e-taha edited this page Nov 12, 2025 · 2 revisions

Selenium E2E Testing - Quick Start Guide

📋 File Layout

e2e/
├── config/test.config.js          # Test configuration & test data
├── helpers/waits.js               # Wait utilities for reliable tests
├── pages/
│   ├── LoginPage.js               # Login page object
│   ├── DashboardPage.js           # Dashboard page object
│   ├── RecipePage.js              # Recipe detail page object
│   └── ProfilePage.js             # User profile page object
└── tests/
    ├── auth.test.js               # Authentication tests
    ├── recipes.test.js            # Recipe interaction tests
    └── profile.test.js            # Profile tests

🚀 Quick Start (5 minutes)

Step 1: Install Dependencies

cd practice-app/frontend
npm install --save-dev selenium-webdriver

Step 2: Download ChromeDriver

# Via npm (easiest)
npm install --save-dev webdriver-manager
npx webdriver-manager update

# Or manually download from:
# https://chromedriver.chromium.org/

Step 3: Update package.json Scripts

Add these to your package.json under "scripts":

{
  "scripts": {
    "e2e": "jest e2e/tests --runInBand",
    "e2e:watch": "jest e2e/tests --watch --runInBand",
    "e2e:chrome": "jest e2e/tests/auth.test.js --runInBand"
  }
}

Step 4: Ensure Your App is Running

npm run dev
# Your app should be at http://localhost:5173

Step 5: Run Your First Test

npm run e2e:chrome

📝 Understanding the Code

Page Object Model (POM) Pattern

Instead of this (bad):

// ❌ Bad - scattered selectors, hard to maintain
test('login', () => {
  driver.findElement({ css: 'input[type="email"]' }).sendKeys('test@test.com');
  driver.findElement({ css: 'input[type="password"]' }).sendKeys('pass123');
  driver.findElement({ css: 'button' }).click();
});

We do this (good):

// ✅ Good - organized, reusable, maintainable
test('login', async () => {
  await loginPage.login('test@test.com', 'pass123');
  expect(await dashboardPage.isDisplayed()).toBe(true);
});

How to Use Page Objects

Each page object encapsulates:

  1. Locators - CSS selectors/XPaths to find elements
  2. Actions - Methods to interact with the page
  3. Assertions - Methods to verify state

Example - LoginPage.js:

class LoginPage {
  // 1. Locators
  emailInput = By.css('input[type="email"]');
  loginButton = By.css('button[type="submit"]');

  // 2. Actions
  async enterEmail(email) {
    const element = await waitForElement(this.driver, this.emailInput);
    await element.sendKeys(email);
  }

  // 3. Assertions
  async isDisplayed() {
    const element = await waitForElement(this.driver, this.loginButton, 5000);
    return await element.isDisplayed();
  }
}

🎯 Test Structure

Each test file follows this pattern:

describe('Feature Group', () => {
  let driver;
  let page;

  // Setup: run once before all tests
  beforeAll(async () => {
    driver = await new Builder().forBrowser('chrome').build();
    page = new MyPage(driver);
  });

  // Cleanup: run once after all tests
  afterAll(async () => {
    await driver.quit();
  });

  // Setup before each test
  beforeEach(async () => {
    await loginPage.navigateTo();
    await loginPage.login(user.email, user.password);
  });

  // Your actual test
  test('should do something', async () => {
    await page.doAction();
    const result = await page.getResult();
    expect(result).toBe(expectedValue);
  });
});

🔍 Key Selenium Concepts

1. Locators - Finding Elements

// Find by ID
By.id('submit-button')

// Find by CSS Selector
By.css('button.login-btn')
By.css('input[type="password"]')

// Find by XPath
By.xpath('//button[contains(text(), "Login")]')

// Find by class
By.className('submit-btn')

// Find by link text
By.linkText('Login')

2. Waits - The Most Important!

❌ Bad - Hardcoded waits:

driver.sleep(3000); // ❌ Slow and unreliable!

✅ Good - Explicit waits:

// Wait for element to exist
await waitForElement(driver, By.id('element'), 10000);

// Wait for element to be visible
await waitForElementVisible(driver, element, 10000);

// Wait for element to be clickable
await waitForElementClickable(driver, element, 10000);

// Wait for URL to change
await waitForUrlChange(driver, '/dashboard', 10000);

3. Common Actions

// Click
await element.click();

// Type text
await element.sendKeys('text here');

// Clear input
await element.clear();

// Get text
const text = await element.getText();

// Get attribute
const value = await element.getAttribute('data-value');

// Check if displayed
const visible = await element.isDisplayed();

// Check if enabled
const enabled = await element.isEnabled();

📊 Test Files Overview

auth.test.js - Authentication Tests

✓ should display login page
✓ should login with valid credentials
✓ should show error with invalid credentials
✓ should have forgot password link
✓ should have register link
✓ should display dashboard after successful login
✓ should display user greeting
✓ should logout successfully

recipes.test.js - Recipe Tests

✓ should display recipes on dashboard
✓ should navigate to recipe detail page
✓ should display recipe title
✓ should display recipe description
✓ should display ingredients
✓ should bookmark a recipe
✓ should unbookmark a recipe
✓ should rate a recipe
✓ should navigate back to dashboard

profile.test.js - Profile Tests

✓ should display profile page
✓ should display user name
✓ should display user email
✓ should display bookmarked recipes count
✓ should edit user name
✓ should edit user bio
✓ should cancel profile edit

🛠️ Making Tests Work With Your App

1. Update Test Data

In e2e/config/test.config.js, update with real test credentials:

testData: {
  validUser: {
    email: 'your-test@example.com',  // Update this
    password: 'your-test-password'    // Update this
  },
  invalidUser: {
    email: 'invalid@example.com',
    password: 'wrongpassword'
  }
}

2. Update Element Selectors

If tests can't find elements, update the locators in page objects:

// In LoginPage.js - if your email input has different selector
emailInput = By.css('input[placeholder="Email"]'); // Update if needed
loginButton = By.xpath('//button[text()="Sign In"]'); // Use XPath if needed

How to find the right selector:

  1. Open app in browser
  2. Open DevTools (F12)
  3. Inspect the element
  4. Copy the selector or create XPath

3. Add data-testid Attributes (Recommended)

Make your tests more reliable by adding data-testid to your components:

// In your React component
<input 
  type="email" 
  data-testid="email-input"  // Add this
  placeholder="Email" 
/>

<button 
  type="submit"
  data-testid="login-btn"    // Add this
>
  Login
</button>

Then use in tests:

emailInput = By.css('[data-testid="email-input"]');
loginButton = By.css('[data-testid="login-btn"]');

🐛 Troubleshooting

Problem Solution
"Element not found" Check selector in DevTools, update locator
"Timeout waiting for element" Increase timeout, verify element loads
"Port already in use" App not running or port conflict - restart
"ChromeDriver version mismatch" Update webdriver-manager: npx webdriver-manager update
"Test times out" Add console logs to debug, check if element exists
"StaleElementReference" Re-find element instead of reusing reference

📚 Next Steps

  1. Run the basic tests and see what needs fixing for your app
  2. Update selectors in page objects to match your app's structure
  3. Add data-testid attributes to your React components for reliability
  4. Create more specific tests for your app's unique features
  5. Integrate with CI/CD (GitHub Actions, Jenkins, etc.)

🔗 Useful Resources


📞 Common Questions

Q: Why use Selenium instead of Just Jest? A: Jest tests individual components. Selenium tests complete workflows with real browsers - catching integration bugs.

Q: How long should E2E tests take? A: Typically 30 seconds - 5 minutes depending on complexity. That's why they're run less frequently than unit tests.

Q: Can I run multiple tests in parallel? A: Yes, but start with sequential (--runInBand) to avoid port conflicts.

Q: How do I test API calls? A: Selenium makes real API calls - great for testing! If you need mocking, use fixtures or intercept requests.


Enjoy testing! 🎉

⚡ Milestone Reports

⚡ Milestone Demo Plan

👥 Team Members

🚀 Project

🧱 Diagrams

Milestone 1 Demo Plan

💬 Communication Plan

🆆 Weekly Reports

09-22 Week 1
09-29 Week 2
10-06 Week 3
10-13 Week 4
10-20 Week 5
10-27 Week 6
11-03 Week 7
11-10 Week 8
11-17 Week 9
11-24 Week 10
12-01 Week 11
12-08 Week 12

👥 Lab Reports

📋 Lab Agendas

📋 Weekly Meeting Agendas

👨‍🏫 Customer Meeting Notes

🧪 Lab Meeting Notes

📅 Meeting Notes

📂 Backend Subgroup Meeting Notes

📂 Frontend Subgroup Meeting Notes

📂 Mobile Subgroup Meeting Notes

📚 Archives

📌 Milestone Report

💬 Communication Plan

📋 Meeting Agendas

📅 Meeting Notes

📂 Backend Subgroup Meeting Notes

📂 Frontend Subgroup Meeting Notes

📂 Mobile Subgroup Meeting Notes

📚 Lecture Notes

🛠️ Team Best Practices

✍️ Guidance

❗ Issues

🚀 Project

👩‍💼 User Scenarios

Click to Expand ⬇️

🗂️ Templates

Clone this wiki locally