Conditional statements – If, Else If, Else task

Conditional statements – If, Else If, Else task

In a nutshell  

The Conditional statements task lets a test case branch its actions during test execution based on whether a stated condition is true or false. Zoho QEngine offers three variants that work together to build decision logic: If evaluates a condition first, Else If checks an alternate condition only when the preceding one fails, and Else runs only when every condition earlier in the same set has failed.

Overview  

The Conditional statements task set gives a test case the ability to make a decision during test execution instead of running the same fixed sequence of tasks on every run. A conditional set is an If statement, followed by zero or more Else If statements and, optionally, one Else statement. If and Else If each evaluate a condition built from a variable, an operator, and an expression; Else takes no condition at all and serves only as the fallback.

QEngine evaluates the statements in a set from top to bottom and executes only the first one whose condition is met, skipping every statement after it in the same set. If none of the If or Else If conditions match, the Else branch runs when one is present. Because the enclosed actions can be any other QEngine task, this construct is how a script reacts to page state, a system variable, a data source parameter, or the outcome of another task, rather than assuming the same result every run.

Syntax  

IF  

Use this form to run a set of actions only when a stated condition is met.

if(<variable> <operator> <expression>)
{
    <Actions>
}

Parameter

Description

variable

Variable holding the value to compare against the expression.

operator

Compares the variable's value against the expression. Supports the relational operators <, >, <=, >=, ==, and !=, and the logical operators && (AND, both conditions must be true) and || (OR, at least one condition must be true) for combining more than one condition in a single statement. ! (NOT) doesn't combine conditions, it negates a single one. The data type being compared determines which relational operators apply: Number, Decimal, and Date-time support all of them, while Text supports only ==.

expression

A literal value, or an expression that evaluates to a value, compared against the variable.

Actions

One or more QEngine tasks or script statements to run when the condition is met. If the condition isn't met, these are skipped and execution moves to the next statement.

Else IF  

Else If must follow an If statement. Multiple Else If statements can be chained after the If to test additional conditions in sequence, each checked only after every preceding condition in the set has failed.

else if(<variable> <operator> <expression>)
{
    <Actions>
}

Parameter

Description

variable

Variable holding the value to compare against the expression.

operator

Compares the variable's value against the expression. Supports the same relational and logical operators as If, subject to the same data-type restrictions.

expression

A literal value, or an expression that evaluates to a value, compared against the variable.

Actions

One or more QEngine tasks or script statements to run when this condition is met and every preceding condition in the set has failed.

Else  

Always preceded by an If or an Else If in the same set, and must be the last statement in that set. Use this form to run a fallback set of actions when nothing earlier in the set matched.

else
{
    <Actions>
}

Parameter

Description

Actions

One or more QEngine tasks or script statements to run when every preceding If and Else If in the set has failed. Else takes no condition of its own.

Examples  

Example 1: Confirming the cart shows exactly one confirmation message  

Store the number of cart confirmation messages shown after adding a product, then use a single If statement to confirm it appeared exactly once.

// Open the Diver Chronomat product page on the ZWatch Commerce website using the Open URL task
openURL("https://zwatch.zohocommerce.com/products/diver-chronomat/3531661000000075722", "same window");
// Add the product to the cart using the Click task
click(".theme-product-qty-and-add-cart");
// Wait until the cart confirmation message becomes visible
wait(10, ".theme-cart-add-success-message", event.SHOW);
// Create a variable 'messageCount' to store the number of cart confirmation messages currently shown
messageCount = getCount(".theme-cart-add-success-message");
if(messageCount == 1)
{
    info("Cart confirmation message appeared exactly once.");
    // output: Cart confirmation message appeared exactly once.
}

where:  

"https://zwatch.zohocommerce.com/products/diver-chronomat/3531661000000075722"

Diver Chronomat product page URL.

.theme-product-qty-and-add-cart

Locator for the Add to Cart button.

.theme-cart-add-success-message

Locator for the cart confirmation message.

messageCount

Variable storing the number of matching confirmation messages, via the Get Count task.

1

Expected count when the message appears exactly once.

Example 2: Logging extra diagnostic detail only during a Preview Run  

Use the $IS_PREVIEW_RUN and $BROWSER system variables with a logical AND to log detailed output only when the test is running as a Preview Run on Chrome, keeping scheduled test plan runs quieter.

// Wait until the Add to Cart button becomes clickable
wait(10, ".theme-product-qty-and-add-cart", event.CLICKABLE);
// Add the product to the cart using the <Click> task
click(".theme-product-qty-and-add-cart");
if($IS_PREVIEW_RUN == true && $BROWSER == "chrome")
{
    info("Preview Run on Chrome, cart action logged with extra detail.");
    // output: Preview Run on Chrome, cart action logged with extra detail.
}
else
{
    info("Cart action completed.");
    // output: Cart action completed.
}

where:  

.theme-product-qty-and-add-cart

Locator for the Add to Cart button.

$IS_PREVIEW_RUN

System variable holding whether the test case is running in Preview Run.

$BROWSER

System variable holding the browser the test case is running in.

true, "chrome"

Expected values that together confirm a Preview Run on Chrome specifically.

Example 3: Confirming the primary product image renders wider than its thumbnail strip  

Stores the rendered widths of two page elements, use the max() number function to report the greater one, then branch across all three statementsbased on which element is actually wider.

// Open the Diver Chronomat product page on the ZWatch Commerce website using the Open URL task
openURL("https://zwatch.zohocommerce.com/products/diver-chronomat/3531661000000075722", "same window");
// Create a variable 'primaryImageWidth' to store the primary product image's rendered width, using the Get Element Width task
primaryImageWidth = getWidth("img[alt='Diver Chronomat']");
// Create a variable 'thumbnailWidth' to store the thumbnail strip's rendered width, using the Get Element Width task
thumbnailWidth = getWidth(ui.zwatch.product-thumbnail-strip);
// Create a variable 'widerElement' to store the greater of the two widths, using the max() number function
widerElement = max(primaryImageWidth, thumbnailWidth);
if(primaryImageWidth > thumbnailWidth)
{
    info("Primary product image is the wider of the two, as expected.");
    // output: Primary product image is the wider of the two, as expected.
}
else if(thumbnailWidth > primaryImageWidth)
{
    info("Thumbnail strip is unexpectedly wider than the primary image, at " + widerElement + " pixels.");
}
else
{
    info("Primary image and thumbnail strip are rendered at the same width, at " + widerElement + " pixels.");
}

where:  

"https://zwatch.zohocommerce.com/products/diver-chronomat/3531661000000075722"

Diver Chronomat product page URL.

primaryImageWidth

Variable storing the primary product image's rendered width, via the Get Element Width task.

ui.zwatch.product-thumbnail-strip

Stored locator for the thumbnail strip.

thumbnailWidth

Variable storing the thumbnail strip's rendered width, via the Get Element Width task.

widerElement

Variable storing the greater of the two widths, via the max() number function.

Example 4: Applying a loyalty discount based on a data source parameter  

Reference a data source parameter directly with the @ syntax and branch the checkout flow across three tiers based on its value.

// Open the checkout page on the ZWatch Commerce website using the Open URL task
openURL("https://zwatch.zohocommerce.com/checkout", "same window");
if(@customerTier == "Gold")
{
    // Apply the Gold-tier discount code using the Set Value task
    setValue(ui.zwatch.discount-code-field, "GOLD10");
    click(ui.zwatch.apply-discount-button);
}
else if(@customerTier == "Silver")
{
    // Apply the Silver-tier discount code using the Set Value task
    setValue(ui.zwatch.discount-code-field, "SILVER5");
    click(ui.zwatch.apply-discount-button);
}
else
{
    info("No loyalty discount applies for this customer tier.");
    // output: No loyalty discount applies for this customer tier.
}

where:  

"https://zwatch.zohocommerce.com/checkout"

Checkout page URL.

@customerTier

Data source parameter referenced directly in the script, supplying a different value on each test iteration.

ui.zwatch.discount-code-field

Stored locator for the discount code field.

ui.zwatch.apply-discount-button

Stored locator for the apply-discount control.

"GOLD10", "SILVER5"

Discount codes applied for each customer tier.

Example 5: Proceeding with login only when a TOTP is generated  

Store the TOTP returned by a configured MFA service and only submit the login form when generation actually succeeded.

// Open the login page using the Open URL task
openURL("https://www.<website_name>.com/<login_page>", "same window");
// Enter the username using the Set Value task
setValue(ui.<login_page>.<username_field>, "chris.morgan");
// Create a variable 'totp' to store the TOTP generated by the configured MFA service
totp = mfa.PORTAL_LOGIN;
if(totp == "")
{
    info("TOTP generation failed, login not attempted.");
    // output: TOTP generation failed, login not attempted.
}
else
{
    // Enter the generated TOTP using the Set Value task
    setValue(ui.<login_page>.<totp_field>, totp);
    click(ui.<login_page>.<submit_button>);
}

where:  

"https://www.\<website_name>.com/<login_page>"

Login page URL.

ui.<login_page>.<username_field>

Locator for the username field.

totp

Variable storing the TOTP returned by the configured MFA service, named PORTAL_LOGIN.

mfa.PORTAL_LOGIN

Returns the TOTP generated from the PORTAL_LOGIN MFA configuration.

ui.<login_page>.<totp_field>

Locator for the TOTP input field.

ui.<login_page>.<submit_button>

Locator for the login form's submit button.

Example 6: Choosing a checkout function based on whether the shopper is signed in  

Branch on whether the shopper is signed in, and instead of running inline actions, call an entirely separate reusable function per branch using the Call Function task.

// Open the Diver Chronomat product page on the ZWatch Commerce website using the Open URL task
openURL("https://zwatch.zohocommerce.com/products/diver-chronomat/3531661000000075722", "same window");
// Add the product to the cart using the Click task
click(".theme-product-qty-and-add-cart");
// Create a variable 'isMember' to store whether the account menu shows a signed-in state
isMember = assertVisible(ui.zwatch.account-menu-signed-in, errorhandling.CONTINUE_ON_ERROR);
if(isMember == true)
{
    // Call the reusable member checkout function from the shopping module using the Call Function task
    shopping.member_checkout();
}
else
{
    // Call the reusable guest checkout function from the shopping module using the Call Function task
    shopping.guest_checkout();
}

where:  

.theme-product-qty-and-add-cart

Locator for the Add to Cart button.

isMember

Variable storing whether the account menu shows a signed-in state, via the Assert Visible task.

ui.zwatch.account-menu-signed-in

Stored locator for the signed-in indicator in the account menu.

shopping.member_checkout()

Reusable function, defined in the shopping module, that completes checkout for a signed-in member.

shopping.guest_checkout()

Reusable function, defined in the shopping module, that completes checkout for a guest.

Example 7: Routing a support ticket by its priority level in a Zoho Creator application  

Store a ticket's priority value from a Zylker Helpdesk application, built on Zoho Creator, and route it to the matching queue, with a defensive final branch for anything outside the expected values.

// Open the Support Tickets report in the Zylker Helpdesk application using the Open URL task
openURL("https://creatorapp.zoho.com/zylker/helpdesk#Report:Support_Tickets", "same window");
// Open a ticket to read its priority using the Click task
click(ui.helpdesk.ticket-row);
// Create a variable 'ticketPriority' to store the priority value read from the open ticket
ticketPriority = getText(ui.helpdesk.priority-field);
if(ticketPriority == "High")
{
    // Assign the ticket to the on-call queue using the Click task
    click(ui.helpdesk.assign-oncall-button);
}
else if(ticketPriority == "Medium")
{
    // Assign the ticket to the standard queue using the Click task
    click(ui.helpdesk.assign-standard-queue-button);
}
else if(ticketPriority == "Low")
{
    // Assign the ticket to the backlog queue using the Click task
    click(ui.helpdesk.assign-backlog-button);
}
else
{
    info("Unexpected ticket priority: " + ticketPriority);
    // output: Unexpected ticket priority: <value>
}

where:  

"https://creatorapp.zoho.com/zylker/helpdesk#Report:Support_Tickets"

Support Tickets report URL in the Zylker Helpdesk application.

ui.helpdesk.ticket-row

Stored locator for the ticket to open.

ticketPriority

Variable storing the priority value read from the open ticket.

ui.helpdesk.priority-field

Stored locator for the ticket's priority field.

ui.helpdesk.assign-oncall-button

Stored locator for the on-call queue assignment control.

ui.helpdesk.assign-standard-queue-button

Stored locator for the standard queue assignment control.

ui.helpdesk.assign-backlog-button

Stored locator for the backlog queue assignment control.

Use cases  

Scenario 1: Confirming the storefront defaults to INR before a currency-switch test runs  

ZWatch Commerce lets shoppers toggle between INR and USD, and a test suite that later checks currency-switch behavior needs to start from a known default rather than whatever currency a prior session left active.

A tester uses Zoho QEngine to confirm the storefront currency selector reads INR before the rest of the currency suite runs, and corrects it back to INR when it doesn't.

Steps  
  1. Open the Diver Chronomat product page in the same window.

  2. Store the currency selector's text.

  3. If the stored text indicates INR, log that the default already holds.

  4. If it doesn't, switch the currency selector to INR.

Implementation  

// Step 1: Open the Diver Chronomat product page on the ZWatch Commerce website in the same window using the Open URL task
openURL("https://zwatch.zohocommerce.com/products/diver-chronomat/3531661000000075722", "same window");
// Step 2: Store the currency selector's text using the Get Text task
currencyLabel = getText(".theme-currency-option-container");
if(currencyLabel.containsIgnoreCase("INR") == true)
{
    // Step 3: Log that the storefront already defaults to INR
    info("Storefront already defaulted to INR.");
}
else
{
    // Step 4: Open the currency selector using the Click task
    click(".theme-currency-option-container");
    // Step 5: Select the INR option using the Click task
    click(ui.zwatch.currency-option-inr);
}

Scenario 2: Falling back to the full product page when the quick-view overlay doesn't open  

The all-products page lets shoppers add an item to the cart directly from a quick-view overlay without opening the full product page, but the overlay depends on the product card being hovered first, and a slow-loading page could mean it never appears.

A tester uses Zoho QEngine to confirm the add-to-cart flow still succeeds even when the quick-view overlay doesn't open in time, by falling back to the full product page instead.

Steps  
  1. Open the all-products page in the same window.

  2. Hover the Diver Chronomat product card to reveal its quick-view button.

  3. Wait for the quick-view button to become clickable.

  4. Click the quick-view button.

  5. Store whether the quick-view overlay became visible.

  6. If the overlay opened, add the product to the cart from inside it.

  7. If the overlay didn't open, open the full product page and add the product to the cart from there.

  8. Wait for the cart confirmation message to become visible.

  9. Confirm the cart confirmation message text.

Implementation  

// Step 1: Open the ZWatch Commerce all-products page in the same window using the Open URL task
openURL("https://zwatch.zohocommerce.com/collections/3531661000000076004/all-products", "same window");
// Step 2: Hover the Diver Chronomat product card to reveal its quick-view button, using the Hover task
hover("[data-zs-product-url='/products/diver-chronomat/3531661000000075722']");
// Step 3: Wait until the quick-view button becomes clickable
wait(10, ".theme-product-quick-view-button", event.CLICKABLE);
// Step 4: Click the quick-view button using the Click task
click(".theme-product-quick-view-button");
// Step 5: Create a variable 'overlayOpened' to store whether the quick-view overlay became visible
overlayOpened = assertVisible(".theme-quick-view-container", errorhandling.CONTINUE_ON_ERROR);
if(overlayOpened == true)
{
    // Step 6: Add the product to the cart from inside the overlay using the Click task
    click(".theme-product-qty-and-add-cart");
}
else
{
    // Step 7: Open the full product page and add the product to the cart from there
    openURL("https://zwatch.zohocommerce.com/products/diver-chronomat/3531661000000075722", "same window");
    click(".theme-product-qty-and-add-cart");
}
// Step 8: Wait until the cart confirmation message becomes visible
wait(10, ".theme-cart-add-success-message", event.SHOW);
// Step 9: Confirm the cart confirmation message text using the Assert Text task
assertText(".theme-cart-add-success-message", "Added to cart", errorhandling.STOP_ON_ERROR);

Scenario 3: Branching on a payment gateway's transaction status  

A checkout's final confirmation actually depends on a third-party payment gateway's asynchronous status, and the page alone can't tell a tester whether that status is complete, still processing, or failed.

A tester uses Zoho QEngine to call the payment gateway's transaction status endpoint through a configured Connection, then reacts differently depending on the status it returns, confirming the order only when the gateway itself reports it as complete, and flagging anything outside the expected values rather than treating it as a routine failure.

Steps  
  1. Open the checkout confirmation page in the same window.

  2. Store the order ID shown on the confirmation page.

  3. Call the payment gateway's transaction status endpoint through the configured Connection.

  4. Store the status field from the response.

  5. If the status is Completed, confirm the order confirmation banner is visible.

  6. If the status is Pending, log that the payment is still processing.

  7. If the status is Failed, log that the order needs review.

  8. If the status is anything else, log it as unexpected.

Implementation  

// Step 1: Open the checkout confirmation page on the ZWatch Commerce website in the same window using the Open URL task
openURL("https://zwatch.zohocommerce.com/checkout/confirmation", "same window");
// Step 2: Store the order ID shown on the confirmation page using the Get Text task
orderId = getText(ui.zwatch.order-id-label);
// Step 3: Call the payment gateway's transaction status endpoint through the configured Connection using the invokeUrl task
paymentResponse = invokeUrl
[
    url: "<payment_gateway_api>/transactions/" + orderId
    type: GET
    connection: "paymentgateway"
];
// Step 4: Create a variable 'transactionStatus' to store the status field read from the response
transactionStatus = paymentResponse.get("status");
if(transactionStatus == "Completed")
{
    // Step 5: Confirm the order confirmation banner is visible using the Assert Visible task
    assertVisible(ui.zwatch.order-confirmed-banner, errorhandling.STOP_ON_ERROR);
}
else if(transactionStatus == "Pending")
{
    // Step 6: Log that the payment is still processing
    info("Payment is still processing for order " + orderId);
}
else if(transactionStatus == "Failed")
{
    // Step 7: Log that the order needs review
    info("Payment failed for order " + orderId + ", flagged for review.");
}
else
{
    // Step 8: Log that the status wasn't one of the expected values
    info("Unexpected payment status for order " + orderId + ": " + transactionStatus);
}

Scenario 4: Auto-escalating a Premium customer's ticket regardless of its priority level  

Consider an organization that uses a Zoho Creator Zylker Helpdesk application to manage support tickets. Tickets are routed by priority, but Premium-tier customers are entitled to escalation regardless of the priority a ticket was filed under.

A tester uses Zoho QEngine to confirm a Premium customer's ticket gets escalated even when its priority field reads Low, rather than following the standard priority routing.

Steps  
  1. Open the Support Tickets report in the Zylker Helpdesk application.

  2. Open a ticket filed under Low priority.

  3. Store the customer tier value from the ticket.

  4. If the customer tier is Premium, escalate the ticket regardless of priority.

  5. If the customer tier isn't Premium, route the ticket to the standard queue.

Implementation  

// Step 1: Open the Support Tickets report in the Zylker Helpdesk application using the Open URL task
openURL("https://creatorapp.zoho.com/zylker/helpdesk#Report:Support_Tickets", "same window");
// Step 2: Open a ticket filed under Low priority using the Click task
click(ui.helpdesk.low-priority-ticket-row);
// Step 3: Store the customer tier value from the open ticket
customerTier = getText(ui.helpdesk.customer-tier-field);
if(customerTier == "Premium")
{
    // Step 4: Escalate the ticket regardless of its priority using the Click task
    click(ui.helpdesk.escalate-button);
}
else
{
    // Step 5: Route the ticket to the standard queue using the Click task
    click(ui.helpdesk.assign-standard-queue-button);
}

Points to note  

  1. An If statement starts a conditional set. It can be followed by one or more Else If statements and, optionally, final Else statement. The Else statement takes no condition of its own.

  2. Use a variable or expression that represents the value you want to evaluate, such as a value returned by Get Text, Get Count, a system variable, or a data source parameter.

  3. Wrap a conditional check around a page action with a preceding Wait task when the value being evaluated depends on an element that loads asynchronously, so the condition reads the settled state.

  4. Combine a conditional branch with Call Function or invokeUrl when a branch needs to execute a reusable flow or retrieve data from an external service.

QEngine evaluates the branches from top to bottom and executes the first branch whose condition is met. If none of the conditions are met, it executes the Else branch if it is present.Use conditional statements when the test flow needs to choose between different actions based on runtime state. If the same action runs in every case and only its input changes, consider using a variable or data source parameter instead of branching.

Previous  

Before learning about the Conditional statements task, ensure that you've learned about the Execute JS task to run custom JavaScript against the current window or frame during test execution.

What's next  

Now that you've learned how to build decision logic using the Conditional statements task, learn how to assign a value to a local variable using the Set Variable task.