Your comprehensive resource for Test Cases, Scenarios, Tips & Scripts
Comprehensive test cases covering various scenarios and functionalities
Verify that users can successfully log in with valid credentials
User is redirected to dashboard and session is established
Username: testuser@example.com
Password: Test@123
Verify that the email field validates input correctly
Error message displayed: "Please enter a valid email address"
Invalid: invalid-email, test@, @domain.com
Valid: user@example.com
Verify search returns accurate results based on query
Relevant results displayed with query highlighted. Results are sorted by relevance.
Query: "automation", "test", "" (empty)
Verify successful payment processing and order confirmation
Payment processed successfully, order confirmation displayed, email sent
Verify application displays correctly on mobile devices
All elements are visible, accessible, and properly sized. No horizontal scrolling required.
Verify file upload accepts only allowed file types and sizes
Invalid files rejected with error message. Valid file uploads successfully with progress indicator.
Real-world test scenarios covering end-to-end user journeys
Scenario: Complete purchase journey from product discovery to order confirmation
Scenario: New user registration with email verification and account setup
Scenario: Generate and export reports with data visualization
Scenario: Ensure consistent functionality across browsers and devices
Scenario: Verify API endpoints and data consistency
Scenario: User settings and application configuration
Professional QA insights, best practices, and productivity tips
Reusable automation scripts and code snippets
// BasePage.js
export class BasePage {
constructor(page) {
this.page = page;
}
async navigateTo(url) {
await this.page.goto(url);
await this.page.waitForLoadState('networkidle');
}
async clickElement(selector) {
await this.page.waitForSelector(selector, { state: 'visible' });
await this.page.click(selector);
}
async fillInput(selector, text) {
await this.page.waitForSelector(selector);
await this.page.fill(selector, text);
}
async getText(selector) {
await this.page.waitForSelector(selector);
return await this.page.textContent(selector);
}
async takeScreenshot(name) {
await this.page.screenshot({
path: `screenshots/${name}.png`,
fullPage: true
});
}
}
// LoginPage.js
import { BasePage } from './BasePage';
export class LoginPage extends BasePage {
constructor(page) {
super(page);
this.usernameInput = '#username';
this.passwordInput = '#password';
this.loginButton = 'button[type="submit"]';
this.errorMessage = '.error-message';
}
async login(username, password) {
await this.fillInput(this.usernameInput, username);
await this.fillInput(this.passwordInput, password);
await this.clickElement(this.loginButton);
}
async getErrorMessage() {
return await this.getText(this.errorMessage);
}
}
// cypress/support/commands.js
// Custom command for login
Cypress.Commands.add('login', (username, password) => {
cy.visit('/login');
cy.get('[data-testid="username"]').type(username);
cy.get('[data-testid="password"]').type(password);
cy.get('[data-testid="login-button"]').click();
cy.url().should('include', '/dashboard');
});
// Custom command for API calls
Cypress.Commands.add('apiRequest', (method, endpoint, body) => {
return cy.request({
method: method,
url: `${Cypress.env('apiUrl')}${endpoint}`,
headers: {
'Authorization': `Bearer ${Cypress.env('token')}`,
'Content-Type': 'application/json'
},
body: body
});
});
// Custom command for waiting and retrying
Cypress.Commands.add('retryUntil', (selector, options = {}) => {
const { timeout = 10000, interval = 500 } = options;
cy.get(selector, { timeout }).should('be.visible');
});
// Usage in tests
cy.login('user@example.com', 'password123');
cy.apiRequest('GET', '/users', {}).then((response) => {
expect(response.status).to.eq(200);
});
// api-helper.js
export class APIHelper {
constructor(request) {
this.request = request;
this.baseURL = process.env.API_BASE_URL;
this.token = process.env.API_TOKEN;
}
async get(endpoint, headers = {}) {
const response = await this.request.get(`${this.baseURL}${endpoint}`, {
headers: {
'Authorization': `Bearer ${this.token}`,
'Content-Type': 'application/json',
...headers
}
});
return response;
}
async post(endpoint, body, headers = {}) {
const response = await this.request.post(`${this.baseURL}${endpoint}`, {
headers: {
'Authorization': `Bearer ${this.token}`,
'Content-Type': 'application/json',
...headers
},
data: body
});
return response;
}
async validateResponse(response, expectedStatus = 200) {
expect(response.status()).toBe(expectedStatus);
expect(response.ok()).toBeTruthy();
return await response.json();
}
}
// Usage in tests
import { test, expect } from '@playwright/test';
import { APIHelper } from './api-helper';
test('API Test - Get User', async ({ request }) => {
const api = new APIHelper(request);
const response = await api.get('/users/123');
const data = await api.validateResponse(response, 200);
expect(data.id).toBe(123);
expect(data.email).toBeDefined();
});
// test-data-generator.js
export class TestDataGenerator {
static generateEmail() {
const timestamp = Date.now();
return `testuser${timestamp}@example.com`;
}
static generateRandomString(length = 10) {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let result = '';
for (let i = 0; i < length; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length));
}
return result;
}
static generateRandomNumber(min = 1, max = 100) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
static generateUserData() {
return {
firstName: `Test${this.generateRandomString(5)}`,
lastName: `User${this.generateRandomString(5)}`,
email: this.generateEmail(),
phone: `+1${this.generateRandomNumber(2000000000, 9999999999)}`,
password: 'Test@123456'
};
}
static getTestDataFromFile(fileName) {
const fs = require('fs');
const path = require('path');
const filePath = path.join(__dirname, 'test-data', fileName);
return JSON.parse(fs.readFileSync(filePath, 'utf8'));
}
}
// Usage
const userData = TestDataGenerator.generateUserData();
const testUsers = TestDataGenerator.getTestDataFromFile('users.json');
// wait-helper.js
export class WaitHelper {
constructor(page) {
this.page = page;
}
async waitForElement(selector, options = {}) {
const { timeout = 30000, state = 'visible' } = options;
try {
await this.page.waitForSelector(selector, {
state,
timeout
});
return true;
} catch (error) {
console.error(`Element ${selector} not found within ${timeout}ms`);
return false;
}
}
async waitForNetworkIdle() {
await this.page.waitForLoadState('networkidle');
}
async waitForAPIResponse(url, timeout = 30000) {
const response = await this.page.waitForResponse(
response => response.url().includes(url) && response.status() === 200,
{ timeout }
);
return response;
}
async waitForElementToBeEnabled(selector) {
await this.page.waitForFunction(
selector => {
const element = document.querySelector(selector);
return element && !element.disabled;
},
selector
);
}
async retryUntil(condition, maxRetries = 5, delay = 1000) {
for (let i = 0; i < maxRetries; i++) {
try {
if (await condition()) {
return true;
}
} catch (error) {
if (i === maxRetries - 1) throw error;
}
await this.page.waitForTimeout(delay);
}
return false;
}
}
// Usage
const waitHelper = new WaitHelper(page);
await waitHelper.waitForElement('#submit-button');
await waitHelper.waitForAPIResponse('/api/users');
await waitHelper.retryUntil(async () => {
return await page.textContent('.status') === 'Complete';
});
// screenshot-helper.js
import fs from 'fs';
import path from 'path';
export class ScreenshotHelper {
constructor(page) {
this.page = page;
this.screenshotDir = path.join(process.cwd(), 'screenshots');
this.ensureDirectoryExists();
}
ensureDirectoryExists() {
if (!fs.existsSync(this.screenshotDir)) {
fs.mkdirSync(this.screenshotDir, { recursive: true });
}
}
async takeScreenshot(name, options = {}) {
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const fileName = `${name}-${timestamp}.png`;
const filePath = path.join(this.screenshotDir, fileName);
await this.page.screenshot({
path: filePath,
fullPage: options.fullPage || false
});
return filePath;
}
async takeScreenshotOnFailure(testName) {
const screenshotPath = await this.takeScreenshot(
`failure-${testName}`,
{ fullPage: true }
);
console.log(`Screenshot saved: ${screenshotPath}`);
}
}
// reporter-helper.js
export class ReporterHelper {
static generateHTMLReport(testResults) {
let html = `
Test Report
Test Execution Report
Test Name
Status
Duration
Screenshot
`;
testResults.forEach(result => {
html += `
${result.name}
${result.status}
${result.duration}ms
${result.screenshot ? `View` : 'N/A'}
`;
});
html += `
`;
return html;
}
}