How to write Test Case in Cypress: (with testing example)

On This Page How to compose Cypress Test CaseCypress E2E Test Case

April 17, 2026 · 9 min read · Tool Comparison

How to publish Test Case in Cypress: (with testing example)

When testing your application, the only way to achieve faster time to production is by automating tests. and executing them is one of the easiest and fastest manner to advance testing if your covering is written in Javascript.

Overview

What is Cypress?

Cypress is a JavaScript-based front-end testing framework catering to web applications. It lets developers and tester indite tests like unit tests, integration trial, and end-to-end tests for different development level.

Benefits of Writing Test Cases on Cypress

  • Leverage End-to-End Test Automation
  • Utilize Automatic Waiting
  • Utilize Time-travel debugging
  • Make use of Real-Time Reloads
  • Interactive Debugging
  • Reduce flaky examination
  • Ease to Use

This tutorial explains how to compose Cypress test cases and takes you through a Cypress testing example.

How to write Cypress Test Case

When writing a Cypress test causa, consider the type of testing that you want to apply. The Cypress UI offers you an easy interface to start running E2E Cypress test scripts or component tests. It also include a wizard that takes you through create the tests.

Consider an example, such as a shopping web application, such aswww.bstackdemo.com. When testing this web app, there might be multiple scenarios that you would need to prove.

Cypress E2E Test Case

An script comprises a test that see for a complete logical flow in the application. So, for our web app,bstackdemo.com, this would mean a complete life cycle of range an order for the earpiece or screen the login flow for the application.

In this guidebook, you will learn to create an E2E tryout that tests for login using the correct certification and a failed test utilize the incorrect credential.

Cypress Component Testing

In a typical SDLC, all modules of the web application are ne'er germinate together. In an Agile environs, each module is germinate over a series of sprints. Though in an ideal cosmos, it is preferred that E2E tests are performed to ensure desegregation between different modules and resulting issues are identified together; you must consent practicalities and optimize your testing procedure to cover iterative development.

In such lawsuit, you can use Cypress ingredient testing. For our instance web application, that could mean testing just thelogin page and checkoutpage in isolation.

Here is a Cypress examine instance to better realise how to write a test case for each of these scenarios.

Test Management Reimagined with AI

Join our live webinar to discover how top QA teams boost test creation speed by 90 % using AI.

Cypress Testing Example

Before you start implementing this instance, ensure that the next requirement are met.

Prerequisites

Run a Cypress E2E test

Running a Cypress E2E test regard installing Cypress in your working directory, create necessary supplementary files, creating your spec file, and then running your test.

Step 1: Install Cypress in working directory

  • Create an E2E directory nominatebstackdemo-E2E.
  • In VSCode, open the directory,bstackdemo-E2E.
  • Click Terminal & gt; New Terminal.
  • Install Cypress habituate the below bidding
npm install Cypress
  • Verify that Cypress and related dependencies are installed.
npx Cypress -- version

Step 2: Create E2E testing configuration files and a spec file.

After you experience instal Cypress, use the Cypress wizard to first create the related form, and so the spec file that tests your E2E scenario.

  • Open the Cypress pad.
npx Cypress open
  • Select the E2E Testing option to start creating the specification file. As there are nospec (* .cy.js)files create yet, the E2E Testing choice evidence the* * Not Configured * * status.
  • Click Continueto create required configuration files in the directory.
  • Select Chromeas the quiz browser, and so clickStart E2E Testingin Chrome. The Cypress splashboard opens.
  • Click Create new specto generate a dummy spec file. Enter a gens,login.cy.js and click Create specification.
  • A check screen with starter code included in the spec file is displayed. Close this window and open VSCode.

Step 3: Edit the E2E trial and run the test

When you create a directory, it include all the required configurations and the spec register that you want to test. The following persona shows the files created and what they mean.

  • E2E:Contains Cypress end-to-end spec files. Each file can be conceive of as a test case in your test suite.
  • fixtures:For data driven examination, include your data .json file here.
  • support:Helper functions, usefulness, any recyclable code, and custom bidding can be placed hither.
  • support/e2e.js:Store global configuration in this folder.
  • support/commands.js:Include tradition command to override existing commands.
  • Cypress.config.js:Includes runtime configurations such as browser manipulation, videos, icon, etc. The following image shows thecypress.config.jsfile that is render for this project:
const {defineConfig} = require (`` cypress ''); module.exports = defineConfig ({projectId: 'tbw9to ', e2e: {setupNodeEvents (on, config) {// implement node event listeners here},},});

Note:If you are utilize BrowserStack to test your project, see the certification.

  • package.json:Includes installed dependencies and option to create custom command shortcuts.

Complete the next steps to run the E2E test:

1. In VSCode, snap the E2E pamphlet in the sailing tree, and so open thelogin.cy.jsfile.

For autonomous testing across multiple user personas, check out SUSATest — it explores your app like 10 different real users.

2. Copy the following code to the file and save it. This code includes two scenarios; foremost to check for successful login, and second to check for an unsuccessful login.

require ('Cypress-xpath '), it ('BstackDemo successful login ', () = & gt; {cy.visit ('https: //www.bstackdemo.com/signin/ ') cy.get (`` # username '') .click (); cy.xpath (`` //div [text () ='demouser '] '') .click (); cy.get (`` # password '') .click (); cy.xpath (`` //div [text () ='testingisfun99 '] '') .click (); cy.get (`` # login-btn '') .click (); cy.get (`` # logout '') .should ('have.text ', 'Logout ') cy.get (`` # logout '') .click (); cy.get (`` # signin '') .should ('have.text ', 'Sign In ')}) it ('BstackDemo failed login ', () = & gt; {cy.visit ('https: //www.bstackdemo.com/signin/ ') cy.get (`` # username '') .click (); cy.xpath (`` //div [text () ='demouser '] '') .click (); cy.get (`` # word '') .type ('ddd {enter} '); cy.xpath ('// * [@ id= '' login-btn ''] ') .click () cy.get (`` # login-btn '') .click (); cy.xpath ('// * [@ id= '' __next ''] /div [2] /div ') .should ('have.text ', 'demouserdddLog InInvalid Password ') cy.log ('invalid password ')})

3. Install theCypress-xpath packagein the directory.

npm i cypress-xpath

4. Run the test use either of the undermentioned options:

  • Using the Cypress dashboard:

a. Click the Specs option from the navigation Zen.

b. Click the login.cy.js spec file to run the exam.

  • Using the terminal in VSCode. In the depot, run the undermentioned bidding:
npx cypress run -- specification cypress/e2e/login.cy.js

To verify if your examination ran successfully, in the Cypress dashboard, detentRuns. The following image shows the successful performance of your E2E tests.

Run a Cypress Component Test

Component testing is an effective approach to test a module in your UI alternatively of an E2E scenario.

Note: Ensure that all the prerequisites are like as mention in the previous subdivision and should be met before you start component testing.

Talk to an Expert

Step 1: Create a sample directory, bstackdemo-comp-testing.

Step 2: Create a react aboriginal app in the directory

As part of component examination, all the component of the app need to be available on the local machine. For this, create a react native app in your local directory.

  • In VSCode, open thebstackdemo-comp-testingdirectory.
  • Create a sample react app:
npm create vite @ latest sample-app -- -- template react
  • Initialize the sampling app to establish dependencies:
cd sample-app & amp; & amp; npm install

Step 3: Install Cypress in working directory

  • In VSCode, open thebstackdemo-comp-testing directory.
  • Click Terminal & gt; New Terminal.
  • Install Cypress expend
npm install cypress -D
  • Verify that Cypress and related dependencies are installed.
npx Cypress -- version

Step 4: Create element testing configuration files and a specification file

After you have installed Cypress, use the Cypress champion to first create the related configurations and the spec file that tests your component testing scenario.

  • Open the Cypress launchpad.
npx Cypress open
  • Select theComponent Testingoption to get creating the specification file. As there are nospec (* .cy.js)files created yet, the ingredient try option shows the* * Not Configured * * status.
  • Confirm theFront-end framework and the Bundler, and then snapNext step.
  • Review the installed dev dependencies and clinkContinue.
  • Review the configuration files bestow and clickContinue.
  • Select Chromeas the testing browser, and then snapStart Component Testing in Chrome. The Cypress dashboard opens.
  • ClickCreate new specto generate a dummy specification file. Enter a name,testcomponent.cy.jsx and click Create specification.
  • A confirmation blind with starter code included in the spec file is displayed. Close this window and openVSCode.

Step 5: Create the react app

The sample app includes a simpletonhello worldmessage. It also includes the logic to accept the name of a person and include that in the how-do-you-do world message.

  • In VSCode, click thesample-app & gt; srcdirectory, and so open theApp.jsx file.
  • Copy the following code that displays Hello world when the exam is run. The codification also consent the name of a soul as input and append to the message:
import {useState} from 'react' export default mapping Test ({name = 'Hello World!, People '}) {const [nameMessage] = useState (name) homecoming (& lt; div & gt; & lt; div id='message ' & gt; Hello Browserstack! {nameMessage} & lt; /div & gt; & lt; /div & gt;)}

Step 6: Edit the Component trial and run the test

1. In VSCode, clicksample-app & gt; Cypress & gt; component directory, and so open thetestcomponent.cy.jsx file.

2. Copy the following code that tests the app functionality:

import Test from ' .. / .. /src/App' describe (Test Component ', () = & gt; {it ('Default Message ', () = & gt; {cy.mount (& lt; Test/ & gt;) cy.get (' # message ') .should ('have.text ', 'Hello World!, People ')}) it ('BrowserStack Name ', () = & gt; {cy.mount (& lt; Test name='BrowserStack'/ & gt;) cy.get (' # message ') .should ('have.text ', 'Hello World! BrowserStack ')})})

3. In VSCode, open the terminal.

4. Run the test using either of the following options:

a. Using the Cypress dashboard:

  • Run
npx cypress unfastened
  • Click the Specsselection from the navigation Elvis.
  • Click the testcomponent.cy.jsx specfile to run the test.

b. Using the terminal in VSCode:

  • In the terminus, run the undermentioned bid:
npx cypress run -- element

To control if your examination ran successfully, in the Cypress dashboard, clickRuns. The following image demonstrate the successful executing of your part tests.

Good Practices

Some of the best praxis that you can note before creating Cypress test causa are:

  • Treat each E2E scenario as an independent test case in isolation, log into applications using programs, and control your application & # 8217; s province.
  • Each specification file must be independent of each early. Reduce interdependency.
  • Use assertions correctly such that Cypress commands progress only when explicit conditions are met.
  • Use the constellation file (* .cy.js) to set your baseURL.

Conclusion

In this article, you learnt about how to structure your test cases and likewise how to split your tests as E2E tests or portion tryout. Though Cypress is robust and offers comfort of creating tests, it perform limit the range of browser and devices that you can test in real clip situations.

For stable testing, you must and for that use a, such as, is a outstanding alternative. Access to multiple device help you predict and handle issues before your product reaches product.

Useful Resources for Cypress

Understanding Cypress

Use Cases

Tool Comparisons

Tags
87,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