Conditional Testing in Cypress: Tutorial

On This Page What is Conditional Testing in Software Testing?

February 07, 2026 · 17 min read · Tool Comparison

Conditional Testing in Cypress: Tutorial

Conditional testing in Cypressenables you to make smarter, more flexible examination handwriting that adapt to dynamic UI elements, varied user run, or environment-specific conditions.

By using conditional logic, you can handle optional modals, popups, or redirects without breaking your tests, making your mechanisation more rich and authentic.

Overview

Why use Conditional Testing in Cypress

  • Prevents test failures on dynamic message
  • Improves tryout resilience and accuracy
  • Reduces false positive from non-critical changes
  • Enables realistic, adaptable test flows
  • Maintains reporting without hardcoding every path

Ways to Use if for Conditional Testing in Cypress:

  • Using .then (): Access purpose DOM factor and employ if logic inside the callback.
  • Using .should (): Evaluate weather during assertions and trigger alternate flows.
  • Using .invoke (): Extract values (like text or attributes) to conditionally branch logic.
  • Checking .length: Use jQuery-style checks ($ el.length) to decide if an element exists.
  • Custom Commands: Encapsulate if logic in reusable Cypress bid for clarity.

This guide explains conditional examination in Cypress, its significance, better practices and more.

What is Conditional Testing in Software Testing?

Conditional testing refers to the practice of action specific examination steps or averment only when certain conditions are met.

It introduces logic into exam cases, such asif, else, or switchconditions, to handle dynamic application behavior. This access assist ensure that tests continue valid and efficacious even when parts of the application are optional, variable, or environment-dependent.

Read More:

Importance of Conditional Testing in Software Testing

As modern application grow more dynamic with lineament fleur-de-lis, user personalization, and variable UI states, conditional logic becomes crucial to maintain test reliability and relevance.

Key intellect to use conditional examination:

  • Handles dynamic UI ingredient like modals, banners, or optional battleground
  • Reduces false exam failures by hop irrelevant steps
  • Improves test stability across different environments (for illustration, dev, staging, production)
  • Supports characteristic toggles and in modern applications
  • Enables smarter, context-aware trial flow for better reportage
  • Increases reusability by avoiding hard-coded assumptions in exam scripts

Read More:

When to use Conditional Testing in Cypress?

Use conditional examination in Cypress when:

This helps keep your tests stable, relevant, and adaptable to real-world user scenarios.

Read More:

Setting up Cypress for Conditional Testing

Before implementing conditional logic in your tests, it & # 8217; s important to properly set up Cypress with the right construction, dependencies, and configurations. Here are the instructions on how to set it up:

Installing Cypress and configuring the environment

Installing all prerequisites firstly in our project is necessary. Refer to the first.

Create a new project pamphlet and set up a new Cypress project after control all the requirement are met.

  1. Create the folder anywhere on your computer, so launch Visual Studio Code by takeFile & gt; Open Folder & gt; Choose the file from the scheme & gt; click Ok.
  2. The next step is to use the & # 8216; npm init -y & # 8217; command in the terminal to render the & # 8216; package.json & # 8217; file in our project. This file initializes the npm project and serves as a dependency management file, allowing us to run npm require directly on the project.
  3. The project name, variation, description, keywords, source, license, and script subdivision are all included in the package.json file. The script subdivision is used to run the test scripts from the terminal.
  4. by using the command to install the most late adaptation of Cypress as given below:
npm install cypress

or use the following dictation to instal the specific version of Cypress that is needed

npm install cypress @ adaptation number

For model, use this command after make the ‘ package.json ’ file.

npm install cypress @ 10.10

Run the & # 8220; npx cypress open & # 8221; command to launch Cypress.

Once Cypress has be launched, select E2E Testing, click Continue, pick a browser, and then chatter Start in that browser.

After selecting & # 8220; Start E2E Testing, & # 8221; a Cypress runner appears, allowing us to create spec files with the & # 8220; .cy.js & # 8221; propagation. A transcript of this file will also be created in Visual Studio Code, where we can indite your test cases.

Creating a basic

An array of is known as a test suite, and it is used to run tests and record their outcomes. You can have a test suite for any of a software covering & # 8217; s fundamental features or a specific sort, like smoke, security test suites, etc. The Cypress approach to organizing numerous attached tests is known as ‘ describe ’. Every describe block is component of a group of tests.

Writing Test Cases with Conditional statement

Assume that when you call your website, the content will vary depending on the A/B campaign your server chooses to broadcast. It could depend on a exploiter & # 8217; s geolocation, IP address, clip of day, position, or former hard-to-control circumstances.

How is it possible to create tryout in this way?

Regulate which campaign is sent or proffer a trusty way to name it.

// navigating to the website to receive session cookies cy.visit ('https: //bstackdemo.com/ ') // executing a petition to fetch // item link to the user 's campaign cy.request ('https: //bstackdemo.com/userDetails ') .its ('body.userSpecificCampaign ') .then ((obtainedCampaign) = & gt; {// implementing specific cypress test codification // dependent on the retrieved campaign type return executeCampaignTests (obtainedCampaign)})

You might now ask your server to inform you the cause you are presently in if it preserve the campaign along with a session.

A session cookie that you can read off from your server may be another way to quiz this:

// Visiting the specified URL cy.visit ('https: //bstackdemo.com/ ') // Retrieving the cookie named 'userCampaignData' cy.getCookie ('userCampaignData ') .then ((extractedCampaign) = & gt; {// Executing the relevant campaign tests using the extracted data return runCampaignTests (extractedCampaign)})

Another viable tactic would be to embed data into the DOM directly, but to do it in a way that makes the data invariably accessible and searchable.

This would not function unless it were present constantly:

// Navigating to the HTML factor cy.get ('html ') // Ensuring the HTML has an dimension named 'data-userCampaign' .should ('have.attr ', 'data-userCampaign ') // Extracting the campaign data and scarper the corresponding test .then ((campaignData) = & gt; {return executeCampaignTesting (campaignData)})

How to use if Statements with Cypress Commands

Cypress commands are asynchronous and chainable, so traditional JavaScript if statements don ’ t work directly with them. To apply conditional logic safely, you need to use method like.then(), .should(), or .invoke()that care resolved values.

Recommended Patterns:

1. Using .then()for DOM-based conditions

Access elements and apply logic inside the callback:

Pro tip: Tools like SUSA can handle this autonomously — upload your app and get results without writing a single test script.

js

cy.get ('body ') .then (($ body) = & gt; {if ($ body.find ('.popup ') .length) {cy.get ('.popup .close ') .click ();}});

2. Using .should()for assertions with fallback flows

Trigger logic found on an expected condition:

js

cy.get ('.status ') .should (($ el) = & gt; {if ($ el.text () .includes ('Failed ')) {// usance handling}});

3. Using .invoke()to extract values for logic

Extract textbook or attribute before applying logic:

js

cy.get ('.price ') .invoke ('text ') .then ((price) = & gt; {if (parseFloat (price) & gt; 100) {cy.log ('Price is high ');}});

These patterns allow Cypress test to behave conditionally based on the state of the app, without breaking its command queue and retry mechanism.

Read More:

Using Conditional Statements in Cypress tests

Mutual use cases for conditional examination in Cypress

  • Users get a & # 8220; welcome wizard, & # 8221; but existing users don & # 8217; t. Can you always close the wizard in lawsuit it appears and snub it when it doesn & # 8217; t?
  • Can you undo stillborn Cypress commands, such as when cy.get () fail to find an element?
  • Attempting to develop dynamical test that react otherwise reckon on the text on the page.
  • What should you do differently depending on whether an element exists?
  • How can you describe for the A/B test that your application conducts?
  • You want to locate every & lt; a & gt; element automatically, and count on which ones you locate, you desire to verify that each link operates.

The basic goal of Cypress conditional testing is to conduct tests on an constituent with multiple potential upshot, each of which may require you to act on a different outcome.

Good Practices for Conditional Statements in Cypress Tests

The base of is compose trusty tests. The key to create effective tests is to give Cypress as much & # 8220; state & # 8221; and & # 8220; facts & # 8221; as you can while & # 8220; defend & # 8221; it from issuing new commands until your application has achieved the state you want it to be to continue.

Understanding how your application behaves is essential to avoid publish flaky trial. For representative,

  • You can not perform conditional testing on the DOM without server-side interpretation and no asynchronous JavaScript.
  • Another scheme is to use client-side JavaScript that does synchronous rendering solely.
  • The fact that the exam writers are unsure of the provided state when conducting conditional test adds a important challenge.
  • Under certain circumstances, embedding a active province reliably and consistently is the only reliable approach to having accurate examination.

Read More:

Working with Conditional Logic in Cypress

The following examples will help you understand conditional examination and how to use it in your test:

Case Study:

Step 1:Visit https: //automationteststore.com/ as the first footstep.

Step 2: Select the Login button.

Step 3: If the alternative to & # 8220; Register Account & # 8221; is not checked, choose it.

/// & lt; reference types= '' cypress '' / & gt; // Describing the test suite describe ('Initial Test Suite ', purpose () {// Defining the test case it ('User Account Creation Test ', () = & gt; {// Navigating to the limit website cy.visit ('https: //bstackdemo.com/ ') // Clicking on the customer card at the top of the page cy.get (' # user_menu_top ') .click () // Checking the account registration option cy.get (' # accountForm_accountregister ') .then (($ inputElem) = & gt; {// Verifying if the account registration option is selected by nonremittal if ($ inputElem.is (': checked ')) {cy.log ('Account enrolment option is selected by default ')} else {// Selecting the account registration option if not selected cy.wrap ($ inputElem) .click ()}})})})

Here is a individual exam example in the examination file name above that will click on the registration option on the web page entirely if it is not already choose by default; otherwise, it will simply print a statement indicate that the option for account registration is already select by nonpayment without carrying out any click action on the enrolment option.

To run the test file, you must first open the Cypress examination smuggler using the& # 8216; npx cypress open& # 8216; dictation and then snap the test file on the test moon-curser. This will start the execution, and the test results will be displayed.

Using assertions with the conditional statement

The cypress-if plugin is where the child command .if () and .else () originate. Any Cypress assertion can be used as the .if (assertion) status; element world is utilize by nonpayment. The tryout follows the & # 8220; IF & # 8221; path and bypasses the & # 8220; ELSE & # 8221; section of the command chain.

describe ('Cypress Conditional Testing Demonstration ', () = & gt; {// Common setup for each trial beforeEach (() = & gt; {// Navigate to the designated website cy.visit ('https: //bstackdemo.com/ ')}) it ('Navigate to ProductPage and Validate, if Present (If Path) ', () = & gt; {// Assert the rubric of the page to be 'StackDemo' cy.title () .should ('eq ', 'StackDemo ') // Check the body of the page cy.get ('body ') .then ((bodyElement) = & gt; {// If ProductPage is found on the page, navigate to it if (bodyElement.find (' [data-jsl10n= '' productPage.name ''] ') .length & gt; 0) {cy.get (' [data-jsl10n= '' productPage.name ''] ') .click ()} // If ProductPage is not found, navigate to InfoPage else {cy.get (' [data-jsl10n= '' infoPage.name ''] ') .click ()}}) // Validate the rubric of the navigated page cy.title () .should ('eq ', 'ProductPage ')}) it ('Navigate to InfoPage and Validate, if ProductPage is Absent (Else Path) ', () = & gt; {// Assert the title of the page to be 'StackDemo' cy.title () .should ('eq ', 'StackDemo ') // Check the body of the page cy.get ('body ') .then ((bodyElement) = & gt; {// If an wrong locator is found, try to navigate to ProductPage (will not occur due to incorrect locater) if (bodyElement.find ('nonExistentLocator ') .length & gt; 0) {cy.get (' [data-jsl10n= '' productPage.name ''] ') .click ()} // If the incorrect locator is not found, navigate to InfoPage else {cy.get (' [data-jsl10n= '' infoPage.name ''] ') .click ()}}) // Validate the rubric of the navigated page cy.title () .should ('eq ', 'InfoPage ')})})

Scenario: Conditional Testing in Cypress for Navigation and Validation

This section walks you through a practical scenario demonstrating how to use Cypress & # 8217; s conditional logic to navigate page and validate elements based on their presence or absence.

Test Suite: & # 8220; Cypress Conditional Testing Demonstration & # 8221;

Objective: The master aim of this trial suite is to formalize the navigation and subsequent page title when interacting with different elements conditionally on the & # 8220;https: //bstackdemo.com/& # 8221; website.

Test Setup: beforeEach Hook

  • Purpose: To control that every test starts from the same initial state.
  • Action: Navigate to & # 8220; https: //bstackdemo.com/ & # 8221; before executing each test case.
  • Expected Outcome: The website should be loaded successfully before each exam begins.

Test Case 1: & # 8220; Navigate to ProductPage and Validate, if Present (If Path) & # 8221;

Objective: To validate the navigation and page rubric when the element associated with & # 8220; ProductPage & # 8221; is present.

Steps:

  1. Title Validation: Ensure the initial page title is & # 8216; StackDemo & # 8217;. Element Check and Interaction:
  2. Condition Check: Determine if the element with data attribute [data-jsl10n= & # 8221; productPage.name & # 8221;] is present.
  3. Plus Path (If): If present, click on the element.
  4. Negative Path (Else): If absent, click on an alternative constituent with datum dimension [data-jsl10n= & # 8221; infoPage.name & # 8221;].
  5. Post-Interaction Validation: Assert that the rubric of the navigated page should be & # 8216; ProductPage & # 8217;.

Test Case 2: & # 8220; Navigate to InfoPage and Validate, if ProductPage is Absent (Else Path) & # 8221;

Objective: To validate the pilotage and page title when the element connect with & # 8220; ProductPage & # 8221; is absent, copy a failure or negative path.

Steps:

  1. Title Validation: Confirm that the initial page rubric is & # 8216; StackDemo & # 8217;. Element Check and Interaction:
  2. Condition Check: Determine if an incorrect/non-existent locator is present to simulate the absence of the desired element.
  3. Confident Path (If): If the incorrect locater is found (unlikely), attempt to snap on the ingredient with [data-jsl10n= & # 8221; productPage.name & # 8221;].
  4. Negative Path (Else): If the incorrect locator is not found (likely), click on the factor with [data-jsl10n= & # 8221; infoPage.name & # 8221;].
  5. Post-Interaction Validation: Assert that the rubric of the navigated page should be & # 8216; InfoPage & # 8217;.

Summary:

Through this test suite, we ensure that the covering can handle dynamical navigation based on the presence or absence of elements, thereby validate the UI & # 8217; s responsiveness and navigation logic under different scenario. This is important for ensuring that exploiter are directed correctly as per the available UI elements and that the corresponding pages are accurately symbolize by their rubric, enhancing the reliability and user experience of the application.

cy.then

When the input box is not see, you need a mechanics to chatter it.

it ('Submits the Agreement Form ', () = & gt; {// Navigating to the specified webpage cy.visit ('https: //bstackdemo.com/agreement.html ') // Checking the agreement checkbox cy.get (' # consent ') .then (($ checkbox) = & gt; {// If the checkbox is already checked, log a content if ($ checkbox.is (': checked ')) {cy.log ('User has already yield consent ')} // If not, click to insure it else {cy.wrap ($ checkbox) .click ()}}) // Clicking the submit button to submit the form cy.get ('button # submitForm ') .click ()})

If the code is unclear to you, you must be conversant with the jQuery selectors and commands. You will also need to use thecy.wrap commandto put the element back into a Cypress chain before using the.click () command.

Using loops and iteration in conditional testing

it ('cy.each Halts Iteration Upon Returning false ', () = & gt; {const veggie = ['carrots ', 'potatoes ', 'tomatoes ', 'peppers '] cy.wrap (veggies) .each ((veggie, index) = & gt; {console.log (index, veggie) if (index === 2) {return mistaken // returning false should stop the iteration. // However, ensure to test and verify this behavior in your specific exam environment.} cy.log ('veggie ', vegetable)}) // cy.each yields the original subject // even if the loop is stopped prematurely .should ('equal ', veggies)})

The snippet above will come to a stop when it determines that k == 2. You can fudge and adjust the loop & # 8217; s control per conditional logic.

Grouping test cases with conditional logic

With this.skip (), which can be applied conditionally based on, for example, an environs variable, you can dynamically skip a test through precondition logic.

beforeEach (role () {// Retrieving the exam filter from environment variables const filterCriteria = Cypress.env ('FILTER_CRITERIA '); // If no filter is provided, proceed without filtering if (! filterCriteria) {homecoming;} // Getting the full title of the current test const currentTestName = Cypress.mocha.getRunner () .test.fullTitle (); // If the current test name does not include the filter standard, jump the test if (! currentTestName.includes (filterCriteria)) {this.skip ();}})

Talk to an Expert

Handling Exceptions and Errors in Conditional Testing

You should consider unsuccessful commands in Cypress to be like to uncaught exceptions in server-side scheduling. In those fate, the system has changed to an unreliable province, making any attempt at recovery impossible. In line, you almost always choose to crash and log.

It is what Cypress is doing when it fails the exam. Reporting the failure, bypassing any remaining command in the examination, and bail out. But here, you need to acquire for argument that Cypress did include error treatment.

Enabling this would lead in error recovery for every command, but only after the corresponding command timeout was reached. It would take a very long time to miscarry because timeouts begin at 4 seconds (and increase from there).

//! Note: Error handling in Cypress dictation is not allowed. //! This code is purely for demonstrative purposes function proceedWithoutWorries () {cy.get (...) .should (...) .click ()} cy.get (' # modal ') .contains ('Dismiss ') .click () .catch ((error) = & gt; {// It 's okay, perhaps the modal did n't subsist // or something else ... no big deal proceedWithoutWorries ()}) .then (proceedWithoutWorries)
  • In the best case, you had wasted at least 4 seconds waiting for the & lt; # wizard & gt; element to exist before we err and moved on possibly.
  • The & lt; # wizard & gt; was conjecture to be rendered, but in the worst-case scenario, it didn & # 8217; t provide within the timeout you were allow.
  • Assume that this resulted from a timer in the queue, a WebSocket substance, a waiting network request, or anything else.
  • In this event, not only did you wait a long time for the & lt; # mavin & gt; factor to appear, but it besides probably led to an error farther down the line on other bidding.

No affair what programme idioms are available to you, you can not establish 100 % deterministic tryout if you can not ascertain the state of your coating reliably.

Debugging and Troubleshooting Cypress Conditional Tests

When work with conditional logic in Cypress, unexpected behavior can arise due to timing issue or incorrect assumptions. Debugging these tests efficaciously is key to maintaining reliableness.

1. Debugging conditional examination with Cypress & # 8217; debugger

A key consideration when selecting an automation framework is debugging. Let & # 8217; s take the scenario when a quizzer has created ten lines of the tryout script, and it fails or throws an error. They must inquire the causes of its failure. Now you can easily create your first condition test with successfully.

2. Using console logs and mistake messages for troubleshooting

On both the Cypress window console and the browser console, testers can print logarithm when using Cypress. Even printing the stack trace to the browser console is an option.

In Cypress, console logs can be used in one of two ways:

  • cy.log () command
  • console.log () by configure cypress project

3. Analyzing test results and fixing failure

Debugging Cypress tests can be done in various ways, each with different levels of complexity. Each proficiency needs to undergo several testing rounds before tester can select one (or more) that good meets their skill set, available resources, and overall convenience.

By allowing test retries, Cypress Cloud can identify, report, and reminder flaky tests from your recorded Cypress test runs in your CI/CD workflow.

Organizing and methodically monitoring can help you identify them as they happen, estimate their severity, and prioritize their fix.

Conclusion

Applications written in JavaScript today are highly dynamical and mutable. Over time, the state and DOM undergo constant change. Conditional testing has the drawback of alone being applicable when the province has stabilized. However, it is oftentimes impossible to recount when a position is stable.

A change that occurs every 10 or even 100 milliseconds could miss your notice. However, a computer will have the ability to monitor those changes. Most of the time, you can not use the state of the DOM to guide your conditional behavior. This results in off-the-wall testing, which Cypress API is built to direct at every stage.

While leveraging a real gimmick cloud like BrowserStack, teams may take reward of diverse advantages. Without external emulators, they will inevitably attain the highest. Additionally, teams preserve a lot of the time and expense needed to build device labs.

For automated examination in an Agile environment, BrowserStack uses a comprising more than 3500+ device-browser-OS combination.

Tags

On This Page

69,000+ Views

# Ask-and-Contributeabout this matter with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free