Cypress 101
Testing has become an integral part of the development life cycle in modern web development. Robust testing tools are crucial for ensuring the reliability and functionality of web applications. One such tool that has gained immense popularity for its simplicity and effectiveness is Cypress. In this blog, we will explore Cypress and delve into the key features that make it a go-to choice for web developers and quality assurance engineers.
Table of Contents
- What is Cypress?
- Key Features of Cypress
- The drawbacks of Cypress
- Who uses Cypress?
- Final thoughts on Cypress
What is Cypress?
Cypress is an open-source end-to-end testing framework for web applications. It is designed to make it easier for developers and QA engineers to write and run tests that simulate user interactions with a web application. Cypress is known for its simplicity, speed, and reliability in testing web applications across different browsers.
Architecture
The majority of testing tools, such as Selenium, function by executing remote commands over a network while running outside of the browser. Cypress is the complete reverse. It runs in tandem with your application within the same run loop.
Cypress is powered by a Node server process. Cypress and the Node process exchange messages and coordinate and carry out tasks for one another continuously. It allows us to react in real-time to events in your application and work outside the browser for tasks requiring a higher privilege because we have access to both the front and back end.
Cypress also reads and modifies web traffic dynamically at the network layer. This gives Cypress the ability to alter code that might conflict with its ability to automate the browser in addition to changing everything entering and leaving the browser.
In the end, Cypress has complete control over the automation process, enabling it to comprehend everything that occurs inside and outside the browser. This indicates that Cypress is superior to all other testing tools in terms of consistency of results.
Key Features of Cypress
Cypress comes fully baked, batteries included. Here is a list of things it can do that no other testing framework can:
Time Travel
Cypress captures screen grabs during your tests. In the Command Log, you can highlight individual commands to see exactly what happened at that point. Each command returns the application or component under test to its original state upon execution when it is hovered over. This allows you to travel back in time to previous states when testing. By default, Cypress keeps 50 tests worth of snapshots and command data for time traveling. If you are seeing extremely high memory consumption in your browser, you may want to lower the numTestsKeptInMemory
in your Cypress configuration.
Debuggability
Put an end to speculating about the reasons behind your test failures. You can debug straight from well-known tools like Developer Tools. Debugging is extremely fast, thanks to Cypress-readable errors and stack traces. Your Cypress test code runs in the same run loop as your application. This means you have access to the code running on the page as well as the things the browser makes available to you.
Automatic Waiting
Cypress employs automatic waiting as a fundamental feature to handle synchronization and ensure reliable test execution. This approach is designed to eliminate the need for explicit waits or delays in test scripts, making the testing process more efficient.
Moreover, it intelligently waits for commands to execute only when the necessary conditions are met. It automatically waits for elements to become visible, interactive, or fulfill specific conditions before proceeding with the next command.
It also has a default timeout for each command, which is set to 4 seconds. Cypress considers it a failure if a command isn’t completed within this time frame. If a command fails due to an element not being immediately available, Cypress retries the command until the specified conditions are met or the timeout is reached.
Cypress is designed to work seamlessly with asynchronous operations in web applications. It automatically handles the timing of these operations, such as API requests or data loading, without requiring additional configuration.
Spies, Stubs, and Clocks
Control and verify the behavior of functions, server responses, and timers. You have easy access to the same features you enjoy from unit testing.
Stubs
A stub is a way to modify a function and delegate control over its behavior to you (the programmer). A stub is most commonly used in a unit test but is still useful during some integration/e2e tests. You generally stub a function when it has side effects you are trying to control.
Common Scenarios:
- You have a function that accepts a callback and wants to invoke the callback.
- Your function returns a
Promise
, and you want to resolve or reject it automatically. - You have a function that wraps
window.location
and doesn’t want your application to be navigated. - You’re trying to test your application’s “failure path” by forcing things to fail.
- You’re trying to test your application’s “happy path” by forcing things to pass.
- You want to “trick” your application into thinking it’s logged in or logged out.
- You’re using
oauth
and want to stub login methods.
Spies
With the help of a spy, you can “spy” on a function by recording its calls and subsequently asserting that the function was called with the correct arguments, that it was called a specific number of times, what the return value was, or even the context in which it was called.
A spy does not alter the function’s behavior; it is kept exactly as it is. A spy is most helpful when you are testing the agreement between several functions and don’t care about potential adverse effects.
Clock
Controlling your application’s date and time can be helpful in certain situations to prevent slow tests or override its behavior. You can use the cy.clock()
command to control the system clock during your tests. This can be useful for testing time-dependent functionality.
Keep in mind that controlling the clock is a powerful feature, but it should be used judiciously. Ensure that your tests accurately reflect real-world scenarios, and don’t rely too heavily on manipulating time unless it’s a crucial part of your application’s functionality.
Network Traffic Control
You can easily test, stub, and control edge cases without having to interact with your server. It is up to you how you stub network traffic.
With Cypress, you can test every stage of an HTTP request’s lifecycle inside your application. Cypress gives you access to the objects containing the request’s details to infer its characteristics. You can even mock and stub the response to a request.
Consistent Results
Cypress architecture doesn’t use Selenium or WebDriver. Say hello to fast, consistent, and reliable tests that are flake-free.
Note
Flaky tests are tests that return both passes and failures despite no changes to the code or the test itself.
Screenshots, Videos, and Test Replay
View the videos of your complete test suite when running from the CLI (Command Line Interface), or view screenshots automatically taken when something goes wrong. Test Replay can be used for zero-configuration debugging by recording the test to Cypress Cloud and replaying it precisely as it ran during the run.
Test Replay in Cypress Cloud allows developers to debug failed test runs accurately and efficiently. It captures every test run detail, enabling developers to replay it and inspect the DOM, network requests, console logs, JavaScript errors, and element rendering as they happened during cypress run
.
Cross-browser testing
Cypress can run tests across multiple browsers. Cypress supports Chrome-family browsers (including Electron and Chromium-based Microsoft Edge), WebKit (Safari’s browser engine), and Firefox.
Excluding Electron, any browser you want to run Cypress tests in needs to be installed on your local system or CI environment. A complete list of detected browsers is displayed within the browser selection menu of Cypress.
Smart Orchestration
After setting up your system to record to Cypress Cloud, you can quickly parallelize your test suite, use Spec Prioritization to rerun failed specs first, and use Auto Cancellation to stop test runs on failures in order to prevent tight feedback loops.
Flake Detection
Discover and diagnose unreliable tests with Cypress Cloud’s Flaky test management. By enabling test retries, Cypress Cloud can detect, flag, and track flaky tests from your recorded Cypress test runs in your CI/CD pipeline.
One way to battle flaky tests is to detect and monitor them as they occur in an organized and methodical manner such that you can assess their severity to assist with prioritizing their fix.
The drawbacks of Cypress
While Cypress is a powerful and popular testing framework, it’s important to be aware of some potential disadvantages and limitations:
Language Support
The number of languages Cypress supports is a major consideration when selecting a framework, so let’s start our list of limitations with that. It is primarily meant to be used with JavaScript and related technologies because Cypress is a testing framework based on JavaScript.
Because TypeScript is a typed superset of JavaScript, it is supported by this framework. Unfortunately, there is a catch: a build tool like Webpack or Rollup will need to be used to transpile your TypeScript code to JavaScript.
Browser Support
The next drawback is the inability to use Cypress with Internet Explorer and Safari browsers. Despite Microsoft’s retirement of Internet Explorer, some legacy apps may still require Internet Explorer.
The most recent versions of Chrome and Electron are compatible with Cypress. But, you would need to install extra browser extensions for other well-known browsers like Microsoft Edge and Firefox.
As a result, these browsers might not have the same degree of support as Electron and Chrome. Thus, some features might not function as intended. You should also run your Cypress tests using the most recent version of Electron or Chrome.
Multi-Origin Testing
The next drawback of Cypress is that it is more challenging to conduct multi-origin testing than it is with Selenium. Issues will surface if your automated testing doesn’t include changing the port or domain during testing.
Version 12.0.0 partially addressed the issue, but you will still need to specify the domain change using the command in such scenarios. In constrast, Selenium has no restrictions on altering the origin domain while conducting tests.
No Support for Non-Browser Environments
Cypress is specifically designed for end-to-end testing of web applications within web browsers. Its architecture and features are optimized for browser interactions and may not seamlessly extend to non-browser environments.
In scenarios where testing involves non-browser platforms, such as mobile applications, desktop applications, or backend services, Cypress may not provide out-of-the-box solutions. Other testing tools or frameworks might be better suited for these use cases.
Learning Curve for New Users
For beginners, especially those new to JavaScript and testing, there might be a learning curve when getting started with Cypress. Understanding concepts like chaining and the asynchronous nature of commands can take time.
No Multi-Tab Support
Cypress is designed to work with a single application state, and its architecture doesn’t naturally support scenarios involving multiple browser tabs or windows. Each Cypress test runs in isolation, and sharing state or interactions across tabs can be complex.
Users attempting to address multi-tab scenarios in Cypress often resort to workarounds, such as using browser APIs or executing custom JavaScript to manipulate multiple tabs. These workarounds may not be as clean or intuitive as handling single-tab scenarios.
XPath Support
Since XPath is one of the primary object locators, it is essential to automation testing. Unfortunately, Cypress’s default behavior does not support XPath.
That being said, you can evaluate an XPath expression and obtain the DOM elements that match it by using the cy.xpath()
command. The cypress-xpath plugin, which requires a separate installation, provides this command.
iFrame Support
Cypress does not support iframes by default. Nevertheless, you can assess iframe actions and obtain the corresponding DOM elements by using the cy.iframe()
command. However, you can only use this command if the cypress-iframe plugin is installed.
Who uses Cypress?
Cypress is used by a wide range of organizations and developers for end-to-end testing of web applications. Here are some categories of users who commonly use Cypress:
Web Developers
Cypress is extensively used by web developers to ensure the functionality and integrity of their web applications. Its JavaScript-based scripting and real-time feedback make it particularly appealing to developers working on modern web technologies.
Quality Assurance (QA) Engineers
QA engineers and testing teams leverage Cypress to conduct end-to-end testing, validate user interactions, and identify and address issues in web applications. The framework’s automatic waiting, time-travel debugging, and interactive test runner contribute to a streamlined testing process.
DevOps Teams
DevOps teams integrate Cypress into their continuous integration and continuous delivery (CI/CD) pipelines to automate testing and ensure that new code changes do not introduce regressions or issues.
Final thoughts on Cypress
Cypress’s unique features, real-time reloading, time-travel debugging, and automatic waiting, coupled with its ease of installation, position it as a powerful tool for web testing. As you delve deeper into Cypress, explore its extensive documentation, community support, and the innumerable possibilities it offers for writing reliable and efficient tests.
Whether you’re a seasoned tester or a developer taking your first steps into testing, Cypress provides a robust foundation for ensuring the quality and reliability of your web applications. Happy testing!
Related articles
Follow our blog
Be the first to know when we publish new content.
Cypress architecture
- Introduction to Cypress - December 18, 2023
- Cypress Installation Step By Step - December 6, 2023
- Serenity BDD and Cucumber Testing - November 20, 2023