Complete Cypress Tutorial: Learn Cypress From Scratch

  • Learning Hub
  • Cypress Tutorial: A Comprehensive Guide With Examples and Best Practices

Cypress is an open-source, full-featured, and easy-to-use end to end testing framework for web application testing. Cypress is a relatively new player in the automation testing space and has been gaining a lot of traction lately, as evident from the number of Forks (2.2K) and Stars (36.6K) for the project.

Unlike Selenium, Cypress is preferred by front-end developers and automation testers who are well-versed with JavaScript. However, Cypress is slowly catching up with Selenium, and the six-month download trend comparison of Cypress and Selenium indicates that the war between the two frameworks will continue to intensify in the coming months.

Cypress

If you’re a developer looking to automate the testing of your application, this Cypress testing tutorial walks through the basics of Cypress, how to use it for end-to-end testing, and more.

If you are preparing for an interview you can learn more through Cypress Interview Questions.

Deep dive into the basics of Cypress and various Cypress commands with the Cypress testing tutorial at LambdaTest.

...

What is Cypress?

Cypress is a renowned end-to-end testing framework that enables frontend developers and test automation engineers to perform Web and API testing. Since it is a JavaScript-based test automation framework, it is widely preferred by the developer community. Cypress is a testing tool that is targeted toward developers and QA engineers. It uses a unique DOM manipulation technique and operates directly in the browser. It supports various browser versions of Google Chrome, Mozilla Firefox, Microsoft Edge(Chromium-based) and Electron.

Note: You can run Cypress testing over the LambdaTest cloud.

The Rise of Cypress Framework

Cypress is a comparatively new testing platform that aims to overcome the challenges of automated frontend testing for applications built with React and AngularJS. It's a quick, easy and reliable tool for testing these applications by running them in their actual browser environments. Since Cypress executes tests on a real browser instance, you wouldn't need to download browser drivers, unlike Selenium.

Check out The State of JS 2021 Cypress testing data on the basis of developer Satisfaction,Interest, Usage and Awareness.

Satisfaction: Since 2019, Cypress has shown a slight dip in the level of satisfaction for developers. Cypress shows a dip from 93% in 2019 to 92% in 2021.

Cypress

Interest: The interest shown by the developers for using Cypress testing framework has also shown a fall from 76% in 2019 to 72% in 2021.

Cypress Interest

Usage: The State of JS 2021 survey shows a significant rise in terms of usage from 26% in 2019 to 43% in 2021.

Cypress Usage

Awareness: As per the State of JS 2021 survey, there is a significant rise in the awareness of the Cypress framework amongst the developers from 63% in 2019 to 83% in 2021.

Cypress Awareness

Under the Experience Over Time section of the State of JS 2021 survey, it also shows:

For 2019: Around 28.5% of developers have shown interest in using Cypress for their testing needs. The lack of awareness of the Cypress framework is at an all-time high i.e., 36.9%. Along with this, only 23.9% of developers would like to use Cypress again in the future.

Cypress 2019 Data

For 2020: The developer interest in using the Cypress testing framework has shown a slight increase as compared to the previous year and now represents 29.9%. There is a significant decrease in the lack of awareness for the Cypress testing framework and is now at 26.2% only. Along with this, the percentage of developers and testers who would like to use Cypress again has significantly increased from 23.9% to 32.9%.

Cypress 2020 Data

For 2021: The developer interest in using the Cypress testing framework is stagnant for this year. The awareness for the Cypress framework among the developers and testers has significantly increased over the past 3 years. Along with this, the percentage of developers and testers who would like to use Cypress again is at an all-time high of 39.1%.

Cypress 2021 Data

Why Cypress?

1. Modern Tool: Cypress is a Javascript-based automation tool that runs in the browser and on Node.js. It is based on Mocha and Chai and is written in Javascript. This makes Cypress fast and reliable for testing almost every website, not only those written in Javascript.

2. Fast to Setup: Cypress has no additional requirements for a standard installation. You do not need any libraries, testing engines, servers, drivers or wrappers. Cypress doesn’t require configuration or additional choices to be made.

3. Fast to Implement and Debug: By providing a Domain Specific Language that is not pure JavaScript, Cypress makes it easier for JS developers in the automated testing community to start using the framework. It is also an approachable tool for experienced QA engineers who are already working with other testing frameworks.

The debugging process in Cypress is streamlined and simple. With native access to every single object, you can easily analyze errors within your application. You can debug your application directly with Chrome DevTools while the tests are being executed in the browser.

4. Fast to Execute: Cypress provides a fast, easy, and reliable way to test your application. It automatically waits for the DOM to be loaded so you don’t have to implement additional waits or set up explicit or implicit waits. Cypress follows everything that happens in your application synchronously—it knows when the page is being loaded and when elements send events.

...

Features of Cypress Testing

  • Cypress gives the ability to capture snapshots during a test run. Hovering over a command in the Command Log displays an event summary that describes each event in a test step.
  • Cypress enables easy debugging from the Developer Tools. Errors are displayed, and stack traces are available for each error.
  • Cypress ensures that synchronization techniques like sleep and wait are unnecessary in test cases. Instead, it waits for actions and checks before proceeding ahead.
  • Cypress ensures the characteristics of the functions, timers, and server responses. This is critical from a unit testing point of view.
  • Cypress can capture a screenshot of the browser window on failure by default. It also records a video of your entire test suite execution running from its command-line interface.
  • Because of its architectural design, Cypress provides quick, steady, and dependable test execution results compared to other tools in automation.
  • Cypress has a good error logging message that describes why our script failed.
  • Cypress has an easy-to-use API and requires no configuration to start with.
  • Cypress supports only JavaScript which makes it a preferred choice for developers as well. However, this adds to the learning curve for testers or developers who aren’t familiar with JavaScript.

Cypress Drawbacks

  • Requires compulsory installation of NPM packages as it is limited to JavaScript only.
  • Does not support multiple tabs while running tests.
  • Does not supports a very broad range of browsers like Selenium WebDriver does.
  • Sole reliance on JavaScript multiplies syntax complexities.
  • Cypress community is not that large and there are not many cypress experts who can help you out with complex issues.

Cypress Architecture

Cypress tests run inside the browser, allowing Cypress to modify the browser's behaviour by listening to the incoming network requests and altering them on the fly. In addition, cypress tests have a lower flakiness rate than Selenium tests since Cypress does not use WebDriver. Instead, spies and stubs can be used at run time to control the behaviour of functions and times. Now, let's look at Cypress architecture.

Cypress Architecture By Sathwik Prabhu

By Sathwik Prabhu

Cypress executes on a NodeJS server that invokes the tested browser (one of the iFrames on the page) for running Cypress tests, which are encapsulated in another iFrame. This can be accomplished by running both the Cypress and NodeJS processes on the same session, thereby allowing Cypress to mock JavaScript global objects. In addition, NodeJS's running process also acts as a proxy that helps intercept HTTP requests, helping Cypress mock these requests during testing.

As of the time of writing, Cypress supports Chrome-family browsers (including Electron and Chromium-based Microsoft Edge) and Firefox.

Selenium’s architecture uses the WebDriver component to communicate with the Browser Driver, which then interacts with the actual browser. The WebDriver routes communications between all its components, making sure that information can flow back to the WebDriver from the actual browser. Developers will need different Browser Drivers for different types of browsers.

On the other hand, Cypress executes tests inside the browser, making it possible to test code in real time as it runs in the browser. Cypress runs on a server process, which makes it possible for Cypress to execute code in the same run loop as the application. Cypress, the test runner created by Facebook, is able to respond to application events in real-time because it constantly communicates with the server process. This also allows Cypress to interact with OS components for tasks outside of the browser, such as taking screenshots.

Browsers Supported by Cypress

Cypress support the following browsers:

  • Chrome
  • Chrome Beta
  • Chrome Canary
  • Chromium
  • Edge
  • Edge Beta
  • Edge Canary
  • Edge Dev
  • Electron
  • Firefox
  • Firefox Developer Edition
  • Firefox Nightly

Supported Browser Versions

  • Chrome 64 and above
  • Edge 79 and above
  • Firefox 86 and above

Here is the list of browsers supported by LambdaTest for running Cypress test scripts.

Supported Cypress Versions

With the newer versions of Cypress releasing, to gain the most from recent improvements and bug fixes, it is recommended that your test scripts use the latest version. The .latest format defines the Cypress versions, ensuring that your test scripts always use the latest minor version.

LambdaTest uses the latest minor version to run the tests when Cypress versions are set as 6, 7, 8 or 9. LambdaTest provides support for all the version, starting from - 6.0.0 to 9.2.0.

Write and execute your code at lightspeed with the help of LambdaTest Cypress examples code index.

...

Selenium vs Cypress: A Detailed Comparison

FeaturesSeleniumCypress
Programming LanguagesPython, C#, Java, Python, Ruby, JavaScriptJavaScript
Browser SupportChrome, Firefox, Internet Explorer, Microsoft Edge, SafariBrave, Chrome, Edge, Firefox, Electron
Test FrameworksPyUnit, JUnit, TestNG, JBehave, Behave, Gauge, Specflow, NUnit, Robot, and more.Mocha JS
Test SetupSelenium Grid Server and browser drivers have to be installed in the test machine. Setup is different for a cloud-based Selenium Grid where only browser drivers have to be installed on the test machine.Node JS, Mocha JS, and Cypress have to be installed on the test machine.
Area of TestingUnit testing, security testing, and integration testing.Unit testing, security testing, and integration testing
IntegrationsWide range of integration options – CI/CD tools, reporting tools, and more.Limited integration support with CI/CD tools when compared to Selenium.
Driver DependenciesAppropriate browser driver has to be installed so that the test script can talk to the corresponding web browser.No driver dependency.
Parallel TestingSupportedSupported
Multi-TabsSupportedNot Supported
Multiple Browser InstancesSupportedNot Supported
Execution SpeedSlowFast as Cypress scripts are executed within the browser.
Time TravelNot SupportedSupported
Real-time ReloadsNot SupportedTests are reloaded when any change is made in the test implementation.
Automatic WaitingNot SupportedNo requirement to add waits or sleep in the tests. Cypress automatically waits for commands and assertions before moving to the next instruction.
Default Screenshots and VideosNot available by default, the developer has to write code to achieve the same.Available by default.
Network Traffic ControlNot SupportedNo network lag as tests are executed within the browser. You can control, stub, and test edge cases without any involvement of the server.
Access to Elements Outside the DOMAccess only to the elements in the DOM.A unique DOM manipulation technique helps Cypress in getting access to DOM elements, timers, service workers, and more.
Documentation and CommunityMature Community with multiple points of support. Average Documentation.Growing Community, Excellent Documentation.
Remote ExecutionSupported. Cloud-based Selenium Grid from LambdaTest can be used to expedite cross-browser testing and automation testing.Not Supported
Spies, Stubs, and ClocksNot AvailableCypress lets you control the behaviour of functions, timers, and server responses with ease.
Mobile TestingMobile Testing with AppiumNot Supported
Test FlakinessTests can be flaky.With Cypress, tests are expected to be non-flaky.

Cypress Learning: Best Practices

After working with Cypress UI testing, here are some of the best practices you should use to avoid anti-patterns in your Cypress automation tests:

1. Login Programmatically: To test most of the functionalities, a user needs to be logged in.

  • Anti-Pattern: Not sharing shortcuts and using the UI to log in.
  • Best Practice: Test your code in isolation, programmatically log into the application and take control of various states in the application.

A very common mistake made by testers is that they often log in to a web page that requires authentication and then redirect to the page that needs testing. But the problem with this approach is that it uses your application UI for authentication, and after the authentication is done, it redirects to the page you want.

The way to deal with this would be to log in programmatically. To sign in programmatically, we need to use the Cypress request command cy.request(). This command makes HTTP requests outside of the browser and can bypass CORS restrictions and other security measures.

2. Using Best-suited Selectors: All tests we write should include selectors for elements. CSS classes may change or be removed, so we must use resilient selectors that can accommodate those changes.

  • Anti-Pattern: Using selectors that are highly brittle and subject to change.
  • Best Practice: Use data-cy attributes to provide context to selectors and keep them isolated from changes in CSS or JavaScript.

The Selector Playground follows these best practices automatically. It prefers elements with data-cy data-test when determining a unique selector because it has the highest priority. We should use data-cy to keep consistency.

When to use cy.contains()?

When you need to select an element with the text present in the page, you can use cy.contains(). However, you must ensure that the selected text always exists.

3. Assigning Commands Return Values: Cypress does not run synchronously, meaning that the return value of any command cannot be assigned to a variable.

  • Anti-Pattern: You cannot assign the return value of a command to a variable declared with const, let, or var.
  • Best Practice: Closures allow you to store what commands yield.

Do not assign the return values of any Cypress command. Enqueueing commands makes them asynchronous, so there is no guarantee that the behavior of the tests will be the same if they depend on the return values.

If you’ve worked with JavaScript enough, then you’re probably familiar with JavaScript promises and how to work with them. You can access the value yielded by Cypress commands using the .then() command.

4. Having Tests Independent of Each Other:

  • Anti-Pattern: Making tests dependent on each other or coupling multiple tests.
  • Best Practice: Tests should always be able to run independently from one another and still pass. Cypress enables developers to run their tests in parallel, which can save time.

The approach to testing your code depends on the previous state of the application. For example, the step of .should(“contain”, “Hello World”) depends on the previous step of clicking the button, and this also depends on the previous state of typing in the input. These steps obviously depend on each other and fail completely in isolation.


5. Avoiding Small Tests With Single Assertion: Cypress is different from running unit tests, which only run a single event at a time, resetting the state between each one.

  • Anti-Pattern: A single assertion for an element can be used to create many tests.
  • Best Practice: Adding multiple assertions in the same test.

Adding multiple assertions to a single test is much faster than creating multiple tests; therefore, you should not be afraid to add multiple assertions to a single test.

6. Using after or afterEach hooks:

  • Anti-Pattern: To clean up the state by using after or afterEach hooks.
  • Best Practice: Clean up state before running the tests.

It is a good idea to wait until after your test ends to write your state clean-up code. This will help you avoid introducing unnecessary failing tests and will speed up your testing performance.

Who Uses Cypress Testing Framework?

Automated testing is an essential part of modern software delivery practices. The need for stable test automation tools has also increased with the increasing demand for quick time-to-market and stable products. Cypress has successfully established its place among other testing frameworks in web automation and end-to-end UI test automation.

Cypress addresses the pain points faced by developers and QA engineers when testing modern applications, such as synchronization issues and the inconsistency of tests due to elements that are not visible or available. As a result, Cypress, a JavaScript-based end-to-end testing framework, is the go-to choice for many frontend developers and test automation engineers for writing automated web tests.

Being an open-source framework, Cypress serves as a lifeline to many freelancer web developers & web testers. A cloud-based Cypress UI testing cloud-like LambdaTest solves the problems mentioned above.

About LambdaTest

LambdaTest is a leading test execution and orchestration platform that is fast, reliable, scalable, and secure. It allows users to run both manual testing and automated testing of web and mobile apps across 3000+ different browsers, operating systems, and real device combinations.

Using LambdaTest, businesses can ensure quicker developer feedback and hence achieve faster go to market. Over 500 enterprises and 2 Million + users across 130+ countries rely on LambdaTest for their testing needs.

What does LambdaTest offer?

  • Run Selenium, Cypress, Puppeteer, Playwright, and Appium automation tests across 3000+ real desktop and mobile environments.
  • Live interactive cross browser testing in different environments.
  • Perform Mobile App testing on Real Device cloud.
  • Perform 70% faster test execution with HyperExecute.
  • Mitigate test flakiness, shorten job times and get faster feedback on code changes with TAS (Test At Scale).
  • Smart Visual Regression Testing on cloud.
  • LT Browser - for responsive testing across 50+ pre-installed mobile, tablets, desktop, and laptop viewports.
  • Capture full page automated screenshot across multiple browsers in a single click.
  • Test your locally hosted web and mobile apps with LambdaTest tunnel.
  • Test for online Accessibility testing.
  • Test across multiple geographies with Geolocation testing feature.
  • 120+ third-party integrations with your favorite tool for CI/CD, Project Management, Codeless Automation, and more.

How To Run Cypress Tests on LambdaTest?

Cypress cloud grids like LambdaTest allow you to perform Cypress testing at scale. LambdaTest allows you to perform automated cross browser testing on an online browser farm of 40+ browsers and operating systems to expedite the test execution in a scalable way. Moreover, it increases the test coverage with better product quality.

To run your first Cypress automation testing script online, refer to our detailed support documentation & GitHub repository. No need to worry about the challenges with Cypress infrastructure. Want to know a fun fact? Your first 100 Cypress automation testing minutes are on us with just a free sign-up. You can also avail benefits of manual cross-browser testing, responsive testing, and more with a lifetime of free access to LambdaTest, the world's fastest-growing cloud Cypress Grid.

Our detailed documentation will help you develop a better functional understanding of the Cypress framework. We also have Cypress Tutorials on our blog page. Finally, kick-start your Cypress UI automation journey by running your first Cypress test script on the LambdaTest cloud.

Cypress Learning Resources

Run your first Cypress test with our detailed blogs and video tutorials:

Blog and Learning Hub Archive:

Video Archive:

Frequently Asked Questions (FAQs)

What is Cypress testing?

Cypress revolutionizes front-end testing with its powerful JavaScript-based framework. By directly operating in the browser, it empowers developers and QA engineers to automate tests effortlessly, leveraging its cutting-edge DOM manipulation technique to eliminate testing challenges.

Why Cypress?

Cypress executes tests directly in the browser. It runs on a server process that powers Cypress to run in the same run loop as your application, so you can be sure that your tests are not slowing down your app. Along with this, Cypress is fundamentally and architecturally different from Selenium, which means you can write faster, easier and more reliable tests.

What is Cypress used for?

Cypress is a great way to test functional applications in the browser. Cypress allows us to create our tests while our application is being developed and runs on all platforms. It gives a fast, easy-to-use debugging platform for all development activities.

How does Cypress work?

Cypress makes it easy to use the Dev Tools while tests run. You can see every console message, every network request, and even time travel back to the state your application was in when commands ran.

What kind of framework is Cypress?

Cypress is a JavaScript end-to-end testing framework that runs on top of Mocha, a feature-rich JavaScript test framework. It also uses a BDD/TDD assertion library and can be paired with any JavaScript testing framework.

What is Cypress automation?

The Cypress tool is a JavaScript testing automation solution used for web automation. It enables teams to create web test automation scripts, written in the de-facto web language that is JavaScript, for web tests.

Is Cypress a framework?

Yes, Cypress is an end-to-end test automation framework for web applications that enables frontend developers and test engineers to write automated web tests in JavaScript, the primary language used for developing websites. The use of JavaScript makes Cypress testing especially attractive to developers.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Did you find this page helpful?

Helpful

NotHelpful