How to write Cypress Tests

On This Page Setting up Cypress for your projectApril 07, 2026 · 9 min read · Tool Comparison

How to write Cypress Tests

Writing Cypress tests is a more effective and flying option for debugging E2E testing and execute them parallel to any pull request as portion of Uninterrupted Integration.

Overview

What is Cypress?

Cypress is a JavaScript-based front-end examination framework catering to web application. It lets developer and testers pen exam like unit trial, integration trial and end-to-end tests for different development stages.

Why Write and Run Tests on Cypress?

  • End-to-End Test Automation
  • Robotic Waiting
  • Time-travel debugging
  • Quick and simple debugging
  • Ease of Use

This article walks you through the fundamentals of indite Cypress tests, including setting up your exam environment, publish test codification, and running and debugging your tests in the.

Setting up Cypress for your undertaking

Before write your 1st test, you must first. Enter the following bid in CMD:

npm install cypress -- save-dev

Once Cypress has been set up, you can launch it by using:

npx cypress open

After installing Cypress, you can use the IDE to make a project and commence creating Cypress trial. The directory cypress/integration/ contains all of the tests.

Also Read:

Understanding Cypress Syntax and Commands

The BDD syntax from Mocha, which is idealistic for both desegregation and unit testing, has been borrow by Cypress. Every test you & # 8217; ll be indite rests on the basic harness that Mocha volunteer, namely:

  • describe ()
  • context()
  • it()
  • before()
  • beforeEach ()
  • afterEach ()
  • after()
  • .only()
  • .skip()

Cypress Commands

Cypress dictationprovide you with the option to create custom functionality and still replace preexist commands. Making a custom dictation is typically a voguish thought when you start to truly understand that you are repeatedly writing the same functionality across several tests, or reiterate yourself.

This command could guide the form of a click, website navigation, or still finding an ingredient. As a result, you will include commands as one of the key components in our test.

Also Read:

Consequently, the 1st command you will execute will be to open the website bstackdemo.com. ‘ Visit ’ is the dictation & # 8217; s name.

You must have heard the frequently apply bidding. It & # 8217; s known as ‘get’:

cy.get ('selector ');

This command returns an element based on the selector it use. In order to locate the components to interact with, you would execute this command.

Also Read:

Typically, you would utilize it to initiate a series of instructions.

The statements in the tests, or commands, can be organized in a chain (or chain, in early words).

This entail that, as you cognize from many examination framework, commands can pass on a subject (or return value) of one command to the subsequent command.

You will utilize bid to mimic the actions a user would take.

it ('BstackDemo ', () = & gt; {cy.visit ('https: //bstackdemo.com/ ') cy.get (`` # signin '') .click (); cy.get (`` # username '') .click (); cy.xpath (`` //div [text () ='demouser '] '') .click (); cy.get (`` # password '') .click (); cy.xpath (`` //div [text () ='testingfun23 '] '') .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 ')})

Execute the machine-driven Cypress end-to-end trial after that, then record and study the termination. Cypress tests may be executed using the Cypress Runner or Cypress CLI.

Writing your first Cypress test

To get, you will create a new file in the integration folder. author.spec.js is what you will call it. The suffix .spec stands for “ specification ”. These are the technical necessary that your application must meet to pass a test for a particular feature or application.

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

You will begin by giving the test suite construction such that this clean JavaScript file may house a test. You are going to use the ‘ describe ’ Hook. The tests are contained and arranged using circumstance () or describe (). In other words, our examination are frame by this strategy. Thus, our test file will appear as follow:

// find-author.spec.js describe ('Find writer at browserstack ', () = & gt; {// ...});

What is describe, it, and expect? These all originate from bundle libraries that Cypress has broil in.

  • ‘ describe ’ and ‘ it ’ get from Mocha
  • ‘ look ’ comes from Chai

Also Read:

Making the real test is the next stage. The method it (), or specify (), symbolize the genuine test. As you can see, yo can capture various tests in a individual file, giving us a variety of fantastic structuring options.

// author.spec.js describe ('Find source at browserstack ', () = & gt; {it ('Find the author Hamid Akhtar ', () = & gt; {cy.log ('This is our maiden test ');});});

If you use Cypress to execute our test, you will see that Cypress launches a browser to carry out the test.

Refer to our to execute your 1st Cypress test utilise BrowserStack. The username and admittance key for BrowserStack is site in your.

Create a real test

A reliable test typically includes three level:

  • Organize the covering state.
  • Action necessitate.
  • Make an assertion regarding the province of the resultant coating.

Now the concept would be that you firstly set the covering in a certain state, then you do something in the coating that change it, and then you verify the new state of the application.

An in-depth look:

  • Go to a website.
  • Look up an element.
  • Engage with that element.
  • Make an asseveration consider the page & # 8217; s content.

Or

Let us get:

  • Visit the home page of BStackDemo (https: //www.bstackdemo.com/).
  • Login employ the login page.
  • Make sure the domicile page loads right.
  • Sign off

Writing the examination playscript for the is the next step after determining the test flow, as shown in the picture and codification below.

You will now go over the commands use in the aforesaid icon.

Also Read:

Organizing your Cypress tests

When Cypress is first started in your codebase, it already has a top-level cypress booklet with a suggested structure. Included in this are additional directory like integration for your spec files, fixtures for JSON datum files, plugins for your cy.task (& # 8230;) office and early configurations, and a support pamphlet for your custom commands and types.

When you run Cypress tests on BrowserStack, if your spec file has errors, the test session keeps running and eventually blocks a parallel that could have be used by another spec. You can get elaborate instructions on how to organise your test runs and trial for better test coverage. Learn how to

Tips for structure your exam and create them maintainable

Here are a few best practices to follow while writing Cypress tests to structure and maintain your exam seamlessly:

  • The & # 8220; Writing and Organizing tests & # 8221; certification explains the fundamentals of test system. Tests should be arrange by Page and components as it is best to test each component separately.
  • To give setting to your chooser and shield them from CSS or JS changes, use data- * attributes.
  • Tests must always be able to be executed separately and still pass.
  • Set province directly / programmatically. It & # 8217; s not always as simple to set state programmatically as it is to direct requests to endpoints. To manually set desired values for the application state in the store, you might need to manually dispatch, say, Vue actions. The Cypress documentation provides a utilitarian example of how to testVue web apps using a REST backend and a Vuex datum store.
  • Try to forbear from needing a third-party server. When interact with third-party services using their APIs, such as testing log-in when your app utilize another supplier through OAuth, always use cy.request ().
  • Don & # 8217; t be touch, just add more.
  • Before bunk tests, houseclean up the state.
  • Use averment or path aliases to keep Cypress from continuing unless a sure condition is fulfilled.
  • In your configuration file, fix a baseURL.
  • Making an assertion fail on purpose allows you to examine the yield and error message to see if you can find why it did so.
  • By utilizing the debugger keyword, you may halt the test & # 8217; s execution. Verify that DevTools are unfastened.
  • Cypress records test run videos, allowing you to compare the failed exam run video to the most recent successful test run if a test fails.

Common mistake while launching Cypress

Here are some common erroneousness to avoid while writing Cypress tests:

  • Not making commands/assertions retry-able
  • Repeating DOM selector and having large, bloated specs files. To overcome this prove a class (page objective) for each page that has the selector and bidding expect for the page. The page objects then serve as a user-friendly abstraction, simplifying the spec file.
  • Use a specific selector for GUI tests that instructs developers when an element is included in a GUI test to create selections more reliable.
  • Due to matter include twist constraints and meshwork latency, real-world apps are asynchronous and sluggish. You are tempted to utilize arbitrary cy.wait command value while developing tests for such apps. Instead, you should watch for visual part, such as the loading to be stop. Cypress command like cy.get, for illustration, wait for the ingredient before making the assertion, of class for a predetermined timeout value that you may adjust.
  • The inability to use more than one domain name in a single test is one of Cypress & # 8217; s limitations. In some tests, it may be necessary to visit more than one area. To accomplish this, you may divide our examination logic into various test blocks and put them all in a single test file.

Benefits of Writing Tests on Cypress

Writing tests on Cypress get with several benefits, which is why it is rather democratic among the test community:

  • Fast and Reliable Testing: Real-time reloading and quick executing help advance testing efficiency.
  • Full-Stack Testing: Facilitates end-to-end, unit, and integration testing within the same model.
  • Easygoing Debugging: Detailed error messages and real-time snapshots simplify the debugging process.
  • Automatic waiting: You don & # 8217; t have to depend on denotative waits, as Cypress smartly waits for elements and request.
  • Ease of Use: Cypress has a simple syntax and efficient built-in features which are easy to use.
  • Time-travel debugging: With Cypress, you can inspect the province of the app at any point during test execution via the time-travel debugging feature.

Why Choose BrowserStack for Cypress Testing

BrowserStack is a cloud-based testing platform that lets you run Cypress tests expeditiously across multiple device-OS-browser combinations. Here are a few reasons why you should choose BrowserStack:

  • : Cypress scat on circumscribed browsers, principally Chrome-based ones. BrowserStack aid you expand your Cypress exam to many other browsers, such as Safari, Edge, IE, and more.
  • Video Recording: The ability to read video of test performance is a substantial welfare of utilize BrowserStack to accomplish Cypress tests.
  • Cloud Infrastructure: This cloud-based platform does not require determine up or maintaining browsers or physical devices topically.
  • Parallel Testing: With, you can run multiple Cypress tryout concurrently, speeding up test execution and finally the release cycles.
  • Real-device testing: BrowserStack volunteer you a immense, let you run Cypress tests on 3500+ real gimmick, browser, and OS combinations, so permit you to examine under.
  • Integrations: BrowserStack offers seamless with several like, Circle CI, Bamboo and more.
  • Scalability: BrowserStack indorse real-device and parallel testing on a cloud-based infrastructure, enabling you to run C of Cypress tests across different environments.

Talk to an Expert

Conclusion

Cypress is a powerful weapon for end-to-end examination. Thanks to its user-friendly interface and full-bodied features, you can write, run, and debug tests seamlessly to validate the functioning of your apps.

To further enhance your testing, you can run Your Cypress Tests on BrowserStack. To speed up the testing procedure, you may use with simultaneously on various browser-device combination using BrowserStack.

Useful Resources for Cypress

Understanding Cypress

Use Cases

Tool Comparisons

Tags
75,000+ Views

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