Estimated reading time: 5.2 mins read
Conditional statements are the backbone of JavaScript-based QA testing. They allow testers to make decisions, handle different outcomes, and validate software behavior under varying conditions. In this blog, we’ll explore the most common QA scenarios where conditional statements are crucial, with clear JavaScript examples suitable for beginners.
What Are Conditional Statements in JavaScript?
In JavaScript, conditional statements are instructions that execute different code blocks depending on whether a condition evaluates to true or false. They are essential for controlling the flow of logic in testing scripts.
Common types include:
if / else if / elseswitchstatements- Ternary operators:
condition ? valueIfTrue : valueIfFalse
In QA, these statements help test different paths, handle edge cases, and validate user interactions.
1. Login and Authentication Scenarios
One of the most common uses of conditionals in QA is validating user authentication.
Example Scenario:
- User enters a username and password.
- Login succeeds only if both are correct.
- Login fails if either field is empty or incorrect.
// Check if both username and password are not empty
if (userName !== "" && userPassword !== "") {
// If both fields are filled, login is successful
console.log("Login successful with User ID " + userName);
}
else
{
// If any field is empty, login fails
console.log("Invalid Username and Password");
}
Why it’s important:
Ensures that authentication behaves correctly for both valid and invalid inputs.
2. API Response Validation
QA testers often check API endpoints to confirm that they return the expected status codes and data.
Example Scenario:
- API returns
200for success,201for created, or400/500for errors.
// Check if the API response status indicates success (200 or 201)
if (response.status === 200 || response.status === 201) {
// If success, log PASS message and show response data
console.log("API Status PASS : Successful Response " + response.status);
console.log("Response body ", response.data);
}
else
{
// If not success, log FAIL message
console.log("API Status FAIL");
}
Why it’s important:
Validates backend behavior and ensures that responses match expectations.
3. UI Visibility Checks
Conditional statements are used to verify if UI elements appear correctly.
Example Scenario:
- “Add to Cart” button should appear only if the product is in stock.
// Check if the product is in stock
if (productStock > 0) {
// If stock is available, show Add to Cart button and product info
console.log("Add to Cart button should be visible. Stock is :", productStock);
console.log("Product info is", productInfo);
/*
Output:
Add to Cart button should be visible. Stock is : 20
Product info is { id: 'sku-1234', name: 'Laptop' }
*/
} else {
// If no stock, hide Add to Cart button
console.log("Add to Cart should not be visible");
}
Why it’s important:
Ensures dynamic content behaves according to business rules.
4. Form Validation Scenarios
Forms often require specific input formats. QA uses conditionals to validate fields.
Example Scenario:
- ZIP code must be exactly 5 digits.
if (formData.zipCode && /^\d{5}$/.test(formData.zipCode)) {
console.log("Form Validation: PASS. ZIP code is valid for USA.");
} else {
console.log("Form Validation: FAIL. ZIP code is missing or invalid for USA.");
}
} else {
// For countries other than USA, ZIP code is not required
console.log("Form Validation: PASS. ZIP not required for", formData.country);
}
Why it’s important:
Prevents invalid data submissions and enforces format compliance.
5. Role-Based Access Testing
Conditional statements help test access control for different user roles.
Example Scenario:
- Only admins can access the dashboard.
// Check if the user's role is "QA Analyst"
if (userData.userRole === "QA Analyst") {
// If true, grant access and display user details
console.log("System access granted to the user ", userData.userName);
console.log("User details are :", userData);
} else {
// If false, deny access
console.log("User cannot access the system");
}
Why it’s important:
Ensures security and proper access control.
6. Payment and Navigation Logic
QA testers use conditionals to handle different outcomes in workflows like payments.
Example Scenario:
- Redirect users based on payment status: success, pending, or failed.
// Expected navigation depending on payment outcome
if (paymentStatus === "success") {
console.log("PASS: Payment success -> redirect to Order Confirmation page.");
} else if (paymentStatus === "pending") {
console.log("INFO: Payment pending -> show pending payment page or status.");
} else {
// For all other statuses treat as failure and send to Payment Failed page
console.log("FAIL: Payment failed -> redirect to Payment Failed page.");
}
Why it’s important:
Validates user experience and error handling during critical workflows.
7. Device and Responsive UI Testing
Different devices may display layouts differently. Conditionals help verify UI responsiveness.
Example Scenario:
- Mobile devices use stacked layout; desktop uses multi-column layout.
// Conditional device expectations
if (deviceType === "mobile")
{
console.log("Device Check PASS: On mobile -> expect hamburger menu and stacked layout.");
} else if (deviceType === "tablet")
{
console.log("Device Check PASS: On tablet -> expect medium layout and touch-friendly controls.");
} else
{
console.log("Device Check PASS: On desktop -> expect full-width menu and multi-column layout.");
}
Why it’s important:
Ensures consistent experience across devices.
8. Automation Retry Logic
Conditional statements are crucial in automation scripts to handle flaky elements or retries.
Example Scenario:
- Retry finding a button up to 3 times if it fails to load.
// Step 1: Initialize retry parameters
let attempt = 0; // Current attempt counter
const maxRetries = 3; // Maximum number of retry attempts
let elementFound = false; // Flag to track if element is found
// Step 2: Try to find the element until maxRetries or until found
while (attempt < maxRetries && !elementFound) {
attempt++; // Increment attempt counter
// Step 3: Simulate finding the element
// We'll pretend the element appears on the 2nd attempt
elementFound = (attempt >= 2);
// Step 4: Log result of this attempt
if (elementFound) {
console.log("Retry Logic: PASS - element found on attempt", attempt);
} else {
console.log("Retry Logic: WARNING - element not found on attempt", attempt, ". Retrying...");
// In real automation, you might refresh the page, wait, or re-locate the element here
}
}
// Step 5: Final check if element was never found
if (!elementFound) {
console.log("Retry Logic: FAIL - element not found after", maxRetries, "attempts.");
}
Why it’s important:
Helps automation handle unpredictable behavior in web applications.
Conclusion
Conditional statements in testing are essential to:
- Validate different user inputs and system responses
- Test edge cases and error scenarios
- Ensure correct UI behavior and access control
- Improve automation reliability
By mastering conditional statements, QA testers can write smarter, more efficient test scripts that catch bugs before they reach end users.
Check out the full code on GitHub
Happy Learning.


Leave a Reply