How to run UI tests in Cypress

On This Page What is Cypress?Cypress ArchitectureJanuary 21, 2026 · 12 min read · Tool Comparison

How to run UI tryout in Cypress

UI testing ensures that your coating ’ s interface behaves as expected for exploiter across different scenario. Cypress proffer a fasting, reliable, and developer-friendly way to run UI tests directly in the browser, making it easier to catch and debug visual and functional issues early in the development cycle.

This article explains how to run UI tryout in Cypress, from specify up your test surroundings to penning and accomplish tryout cases.

What is Cypress?

is an end-to-end testing framework built for modern web applications. It allows developers and QA engineers to compose and run tests directly in the browser. It offers real-time reloading, powerful debugging tools, and a uncomplicated API for interacting with web elements.

Unlike traditional Selenium-based instrument, Cypress runs in the like run loop as the coating, giving it better access to the and mesh requests, which leads to faster and more reliable test execution.

Cypress Architecture

Cypress has a unique architecture that sets it apart from traditional testing tools like Selenium. Instead of running outside the browser and communicating over a network, Cypress executes directly inside the browser alongside your coating.

Here ’ s a breakdown of its architecture:

1. Test Runner (Runs Inside the Browser)

The injects test code directly into the browser where your application is running. This allows the test runner to accession the DOM, local storage, cookies, and other browser APIs natively. Because tryout run in the like event cringle as the application, the test runner assure faster and more stable executing equate to traditional testing tool.

2.Node.js Backend (Runs Outside the Browser)

While the tests run inside the browser, Cypress also lam a server in the ground. This handles chore that browser can not, such as:

  • Reading and writing file such as screenshots, videos, and habitue
  • Managing network requests
  • Communicating with the operating system

3. Browser Automation Layer

Cypress uses a custom browser automation stratum, not WebDriver, to control the browser and simulate existent user interactions like chink, typewriting, and scrolling.

4. App and Test Execution in the Same Context

Unlike Selenium, which motor browsers remotely, Cypress runs the test codification in the like context as your application. This makes it easygoing to:

  • Access and assert application state
  • Wait for element without demand explicit hold
  • Debug using browser dev tools

5. Dashboard (Optional)

Cypress also offers a Dashboard Service that provides brainstorm into test runs, include log, screenshots, and videos. This is especially useful when tests run in CI pipelines.

How to Perform Cypress End-to-End UI Testing

End-to-end (E2E) UI testing ensures that your intact application flowing work as wait from the user & # 8217; s position. Cypress makes it easy to simulate real user interactions in the browser and validate UI behavior across Page and element.

To get started, set up your development surround with the following prerequisite.

Install Node.js

  • Go to the Node.js download page
  • Select your operating system and download Node.js (LTS version recommended)
  • Install the Node.js binaries

Install Visual Studio Code (Optional but Recommended)

  • Go to the Visual Studio Code download page
  • Download and install the editor

Step 1: Create an empty directory (ex: cypress-e2e)

Create an empty folder that helps to install and configure cypress

Step 2: Launch Open Empty directory and Launch Terminal

  • Launch the VSCode app instal as a requirement
  • Open the newly make folder fromFile Menu
  • Navigate to theTerminal menu
  • Click on theNew Terminal

Step 3: Install Cypress

The Cypress initiation command installs all required dependencies. To instal Cypress use the below command

npm install cypress

Cypress automatically creates the package.json folder in your project root pamphlet during the installation.

Step 4: Open the Cypress

Cypress needs to do initial settings, you involve to enter the open command to start the cypress window.

npx cypress open

Note: Cypress may throw the verification failed error, entering theopencommand again should purpose the issue.

Step 5: Choose the alternative on the Cypress window

Once you inscribe the open command, the Cypress window will be launched and choose the configuration.

  • Choose the Testing Type: When you run the unfastened command, the Cypress window opens. Choose the examination character. In our suit, it is end-to-end examination.
  • Configuration Files: The configuration files window pops up, review them and Click keep. Cypress creates the configuration settings after this step.
  • Choose a Browser: Next, You necessitate to choose the hope browser from the available options. For the demo purpose let & # 8217; s take Chrome and dogStart e2e Testing in Chrome
  • The Cypress test contrabandist window opens up, pawlcreate new empty spec.
  • Enter the craved spec gens, and click on Create Spec
  • Enter the gens asdemo.cy.js
  • The instance spec will be create clickOkay,run the spec.

The demo tests start running. At this point, your project directory tree looks as shown below.

Understanding the Cypress directory and file

  1. e2e folder:Contains Cypress end-to-end specs
  2. fixtures folder:Any data which can be used inside the specs can be placed here
  3. support folder:Helper functions, utilities, any recyclable code, and custom commands can be placed here.
  4. support/e2e.js:Outstanding place to put the global configuration and recyclable code
  5. support/commands.js:In this file, you can create custom commands or override be commands
  6. cypress.config.js:This file contains run clip configurations such as baseURL, reporter, videos, screenshot choice, etc.
  7. package.json:This file tracks all installed dependencies and allow you to make a custom commands shortcut

Step 6: Create a sample test

You have givendemo.cy.jsas an exemplar specification name, which is already create as part of Cypress apparatus. Let & # 8217; s modify the demo.cy.js with actual use causa.

Let & # 8217; s consider the scenario

  1. Navigate to Browserstack dwelling and control home page is loaded successfully
  2. Click on the Pricing menu, and control if all the product names are listed.

Below is the cypress test spec for the above scenario

//demo.cy.js describe ('Browserstack Demo ', () = & gt; {beforeEach (() = & gt; {cy.viewport (1280, 1000)}) it ('should control home page ', () = & gt; {cy.visit ('https: //browserstack.com ') cy.get (' # logo ') .should ('be.visible ') cy.title () .should ('eq ', 'Most Reliable App & amp; Cross Browser Testing Platform | BrowserStack ')}) it ('should verify Pricing page ', () = & gt; {cy.get (' a [title= '' Pricing ''] ') .first () .click (); cy.get (' a [data-item-id= '' alive ''] ') .should ('contain.text ', 'Live ') cy.get (' a [data-item-id= '' automate ''] ') .should ('contain.text ', 'Automate ') cy.get (' a [data-item-id= '' percy ''] ') .should ('contain.text ', 'Percy ') cy.get (' a [data-item-id= '' app-live ''] ') .should ('contain.text ', 'App Live ') cy.get (' a [data-item-id= '' app-automate ''] ') .should ('contain.text ', 'App Automate ')})})

Home page verification

  • cy.visit () Navigates to the BrowserStack home page
  • cy.get () is chained with assertions should () to verify the visibleness of the logo
  • cy.title () is chained with the assertion (should) to verify the title is correct

Pricing menu check

The click activeness is performed utilisecy.get () .click ()on the pricing card

Once it is landed on the pricing menu, all several locators text are asserted to verify the product itemization on the pricing menu.

Step 7: Execute the test causa

Cypress allows execution through the command line or use the Cypress window (UI)

SUSA automates exploratory testing with persona-driven behavior, catching bugs that scripted automation misses.

Execute cypress UI examine using cypress window

  • Enter the bidding npx cypress open
  • Navigate to the Test smuggler window
  • Click on demo.cy.jsto start execution

Cypress test execution apply bid line

Use the below command to execute Cypress UI tests in the command line

npx cypress run -- spec cypress/e2e/demo.cy.js

Read More:

How Run Cypress Component UI Testing

Component involves testing individual UI portion & # 8217; visual and interactional behavior during development. This allows for faster feedback and delivery. Unlike, component UI examination is execute in isolation on single part.

Cypress supports component UI screen from version 10 and above, and it work with major frameworks such as, Vue, and.

To get get, you want to set up your development environs with the compulsory tools.

Install Node.js

  • Go to the Node.js download page
  • Select your operating system and download Node.js (LTS variant recommended)
  • Install the Node.js binary

Install Visual Studio Code (Optional but Recommended)

  • Go to the Optical Studio Code download page
  • Download and install the editor

Step 1: Create a New Folder and Open it in VS Code

Start by setting up a dedicated pamphlet for your component UI tests. This keeps your tryout files organized and separate from former projects.

  • Create a new folder for constituent testing (for example, cypress-component-demo)
  • Open the folder in VS Code apply theFile menu > Open Folder

Step 2: Clone the Simple react App

As components require to be present locally, you need to make a sample react app and components

Note: if you are already experience the component create in your development framework you can use the like.

On the VSCode terminus enter the below command

npm create vite @ latest my-awesome-app -- -- template react

Step 3: Install the dependencies

Switch to foldermy-awesome-appand participate the below bid to install the dependencies.

npm install

The above command clones the simple react app that can be used for component testing.

Step 4: Install the Cypress

Install Cypress using the below command

npm install cypress -D

Step 5: Configure Cypress for component testing

  • Open Cypress
npx cypress open
  • Choose Component testingfrom the Cypress window
  • TheProject Setup windowautomatically detects the Framework and builder so clickNext.
  • Next, Cypress verifies all required dev dependencies are present. ClickContinue
  • Based on the installed framework and dependency Cypress make the configuration file. Review them, and clicks Continue.
  • Choose the browser: You can choose any browser, for simplicity choose Chrome and pawlStart Component Testing in Chrome.

At this point, the test moon-curser shows up. Do not do anything, just close the Cypress window.

The Project Structure appear as below

Step 6: Create a simple element

Navigate tomy-awesome-app/srcand create a file withDemoComponent.jsx

Create a simple element with a greetings message

import {useState} from 'react' export default purpose Demo ({greetings = 'Good Morning '}) {const [greetingMessage] = useState (greetings) homecoming (& lt; div & gt; & lt; div id='message ' & gt; Hello Browserstack! {greetingMessage} & lt; /div & gt; & lt; /div & gt;)}

In the above code, the nonremittal greet substance isHello Browserstack! Good Morning,

However, the demo part take optional parameter greeting messages you can legislate it like Good Evening, etc.

Let & # 8217; s test this using Cypress

Step 7: Create Cypress Component Test

Navigate to Cypressdirectory and create a directory with the namecomponent.

Create a file inside thecypress/componentleaflet and name it asDemoComponent.cy.jsx

Let ’ s create two test causa

  1. Verify the nonremittal welcome message
  2. Verify the message by sending the parameter & # 8220; Good Evening & # 8221;
import Demo from ' .. / .. /src/DemoComponent' describe ('Demo Component ', () = & gt; {it ('Default Message ', () = & gt; {cy.mount (& lt; Demo/ & gt;) cy.get (' # substance ') .should ('have.text ', 'Hello Browserstack! Good Morning ')}) it ('Good Evening Message ', () = & gt; {cy.mount (& lt; Demo greetings='Good Evening'/ & gt;) cy.get (' # message ') .should ('have.text ', 'Hello Browserstack! Good Evening ')})})

The above code,cy.mount ()mount your element

cy.get()is apply for let the locater on the browser and assertion is used for verify the textbook

Step 8: Execute the Cypress part tests

  • Open the Cypress window using
npx cypress exposed
  • Navigate to the Cypress test runner window
  • Choose theDemoComponent.cy.jsxand execute the test

You can too use the Cypress command line tool to accomplish the test

npx cypress run -- component

The above command executes component exam in headless mode and the results will be testify in command line.

Cypress Tips and Tricks

Make the most of Cypress for UI testing with these hard-nosed hint and tricks to write cleanser, faster, and more honest tests:

1. Use data- * Attributes for Selectors

Avoid by using stable selector like data-cy, data-test, or data-testid instead of class or ID picker that may alter with styling.

& lt; button & gt; Submit & lt; /button & gt;

2. Leverage cy.intercept () for Network Control

Stub or monitor API requests employcy.intercept ()to simulate backend behavior and speed up test execution.

cy.intercept ('GET ', '/api/users ', {fixture: 'users.json '}) .as ('getUsers ');

3. Use beforeEach () to Reduce Repetition

Place reduplicate setup steps insidebeforeEach ()to avert duplicating code across tests. This keeps your clean and leisurely to maintain.

beforeEach (() = & gt; {cy.visit ('/login ');});

4. Add Custom Commands for Reusability

Use Cypress.Commands.add () in cypress/support/commands.jsto define reclaimable actions. This helps you write cleaner tryout by moving repeated steps into a individual, easy-to-use bidding.

Cypress.Commands.add ('login ', (email, word) = & gt; {cy.get (' # email ') .type (e-mail); cy.get (' # password ') .type (password); cy.get ('form ') .submit ();});

5. Use .should () Assertions Wisely

Chain asseveration to verify element states understandably and avoid unnecessary waits. Chaining assertions makes tests easier to read and avoids unnecessary retries or delays, leading to faster and more stable tests.

cy.get ('.alert ') .should ('be.visible ') .and ('contain ', 'Success ');

6. Avoid Hard Waits (cy.wait)

Instead of the hard-codedcy. waiting (), use dynamic waits likecy.get () .should ()or alias to wait for requests or elements. Instead, use dynamic postponement likecy.get () .should ()or web aliases to expect for constituent or asking to complete only when necessary, improving both test speed and stability.

7. Run Tests in Headless Mode for CI

Use cypress run & # 8211; headlessto execute tests without establish a visible browser. This speeds up performance, reduces resourcefulness usage, and fits seamlessly into CI pipelines where no UI is postulate.

Read More:

Run End-to-End UI Tests on BrowserStack

is a testing program that lets you run your Cypress end-to-end UI tests on a wide range of literal browsers and operating systems without managing your own infrastructure. Here & # 8217; s why you ’ d choose BrowserStack for E2E testing with Cypress:

  • Access to existent environments:Test on hundreds of real background and nomadic browsers, including multiple versions of Chrome, Firefox, Safari, and Edge hosted in the cloud.
  • : Run test across multiple browser and OS combination at the like time to reduce test execution clip and speed up release cycle.
  • :Connect BrowserStack to CI/CD tools like GitHub Actions, Jenkins, or GitLab so that each commit automatically triggers cross-browser test.
  • :Get screenshots, video recordings, console logs, and network information for every exam to quickly name and resolve UI issues.

Here ’ s how to use BrowserStack to run end-to-end UI tests.

1. Install BrowserStack using the below bid

npm install -g browserstack-cypress-cli

2. Create a browserstack.json file using the below command

browserstack-cypress init

3. Open the browserstack.json file

  • Add the username and access_key
  • Specify the cypress.conf.js file path

4. Execute the Cypress tests on BrowserStack

browserstack-cypress run

Talk to an Expert

Conclusion

Cypress enables teams to get UI matter early and render consistent user experiences by volunteer real-time reloading, automatic postponement, and a developer-friendly API. These lineament make it easier to progress, test, and maintain reliable front-end workflows throughout the maturation lifecycle.

To farther enhance your testing, bunk Cypress tests on BrowserStack countenance you to formalize UI behavior on real devices and browsers without keep any substructure. This ensures your covering works seamlessly across different platforms, improves examination reportage, and supports quicker, more confident releases.

Tags
94,000+ Views

# Ask-and-Contributeabout this topic 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