Conditional Testing in Cypress: Tutorial
On This Page What is Conditional Testing in Software Testing?
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. Why use Conditional Testing in Cypress Ways to Use if for Conditional Testing in Cypress: This guide explains conditional examination in Cypress, its significance, better practices and more. 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: 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: Read More: Use conditional examination in Cypress when: This helps keep your tests stable, relevant, and adaptable to real-world user scenarios. Read More: 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. or use the following dictation to instal the specific version of Cypress that is needed For model, use this command after make the ‘ package.json ’ file. 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. 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: 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: 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 2. Using .should()for assertions with fallback flows Trigger logic found on an expected condition: js 3. Using .invoke()to extract values for logic Extract textbook or attribute before applying logic: js 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: Mutual use cases for conditional examination in Cypress 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. 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, Read More: 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. 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. 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. 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. Objective: To validate the navigation and page rubric when the element associated with & # 8220; ProductPage & # 8221; is present. Steps: 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: 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. 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 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. 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). 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. 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: 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. 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. On This Page # Ask-and-Contributeabout this matter with our Discord community. Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed. Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.Conditional Testing in Cypress: Tutorial
Overview
What is Conditional Testing in Software Testing?
Importance of Conditional Testing in Software Testing
When to use Conditional Testing in Cypress?
Setting up Cypress for Conditional Testing
npm install cypress
npm install cypress @ adaptation number
npm install cypress @ 10.10
// 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)})// 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)})// 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
cy.get ('body ') .then (($ body) = & gt; {if ($ body.find ('.popup ') .length) {cy.get ('.popup .close ') .click ();}});cy.get ('.status ') .should (($ el) = & gt; {if ($ el.text () .includes ('Failed ')) {// usance handling}});cy.get ('.price ') .invoke ('text ') .then ((price) = & gt; {if (parseFloat (price) & gt; 100) {cy.log ('Price is high ');}});Using Conditional Statements in Cypress tests
Good Practices for Conditional Statements in Cypress Tests
Working with Conditional Logic in Cypress
/// & 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 ()}})})})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
Test Suite: & # 8220; Cypress Conditional Testing Demonstration & # 8221;
Test Setup: beforeEach Hook
Test Case 1: & # 8220; Navigate to ProductPage and Validate, if Present (If Path) & # 8221;
Test Case 2: & # 8220; Navigate to InfoPage and Validate, if ProductPage is Absent (Else Path) & # 8221;
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 ()})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)})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 ();}})Handling Exceptions and Errors in Conditional Testing
//! 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)Debugging and Troubleshooting Cypress Conditional Tests
Conclusion
Related Guides
Automate This With SUSA
Test Your App Autonomously