Ever used Selenium? Do you remember installing a language driver to use it or writing tests for it? Cypress is similar to Selenium but comparatively better. It runs your browser and within the same process, it runs tests. Cypress is an End-to-End test suite
With Cypress, you can easily create tests for your modern web applications, debug them visually, and automatically run them in your continuous integration builds.
What can be done using Cypress
- Test directly in the browser: Watch your end-to-end and component tests run in real-time as you develop your applications. Cypress’s simple, yet powerful API runs as fast as your browser can render content.
- Hassle free, be more productive: Installing Cypress and writing your first passing test is a breeze. There are no servers, drivers, or other dependencies to install or configure.
- Debug using known tools: Because Cypress runs directly in the browser, you can debug failed tests using the in-browser developer tools you already know and love.
- Easy integration with CI provider: Easily integrate Cypress with your current CI provider. Run Cypress in CI, and you will know as soon as there is a failure. We make it simple to run in CI. Use our Docker images, or bring your own.
- Review and debug failures visually: Play back videos of your tests as they failed, read friendly stack trace errors, and never guess why another test failed.
- Integrate seamlessly into your workflow: Plug Cypress into any CI pipeline, and you can manage test results as a team thanks to native integrations with Slack, GitHub, GitLab, JIRA, and more.
What Features does Cypress offers
Cypress comes fully baked, batteries included. Here is a list of things it can do that no other testing framework can:
- Time Travel: Cypress takes snapshots as your tests run. Hover over commands in the Command Log to see exactly what happened at each step.
- Debuggability: Stop guessing why your tests are failing. Debug directly from familiar tools like Developer Tools. Our readable errors and stack traces make debugging lightning fast.
- Automatic Waiting: Never add waits or sleeps to your tests. Cypress automatically waits for commands and assertions before moving on. No more async hell.
- Spies, Stubs, and Clocks: Verify and control the behavior of functions, server responses, or timers. The same functionality you love from unit testing is right at your fingertips.
- Network Traffic Control: Easily control, stub, and test edge cases without involving your server. You can stub network traffic however you like.
- Consistent Results: Our architecture doesn’t use Selenium or WebDriver. Say hello to fast, consistent and reliable tests that are flake-free.
- Screenshots and Videos: View screenshots taken automatically on failure, or videos of your entire test suite when run from the CLI. Record to Cypress Cloud to store them with your test results for zero-configuration debugging.
- Cross browser Testing: Run tests within Firefox and Chrome-family browsers (including Edge and Electron) locally and optimally in a Continuous Integration pipeline.
- Smart Orchestration: Once you’re set up to record to Cypress Cloud, easily parallelize your test suite, rerun failed specs first with Spec Prioritization, and cancel test runs on failures with Auto Cancellation for tight feedback loops.
- Flake Detection: Discover and diagnose unreliable tests with Cypress Cloud’s Flaky test management.
What are key advantages of Cypress
- Architecture
- Native access
- New kind of testing
- Shortcuts
- Flake resistant
- Debuggability
- Trade offs
How to install Cypress
Cypress is a Node.JS package. Hence installing cypress
is like installing the NPM package. Fire up a terminal, traverse to the project directory, and run:
npm install cypress --save-dev
This will install the cypress
package as a local dependency and add it to your package.json
file
Note: Make sure that you already have an npm project containing
package.json
file in the root of your project to ensure cypress is installed in the correct directory.
If you prefer yarn
over npm
. Then instead of running the previous command, you shall run:
yarn add cypress --dev
How to run Cypress
Running cypress
Once you have cypress
installed as a package. you can start cypress using following commands. Fire up terminal and navigate to project directory. If terminal is already open then make sure you are in project directory. If you have installed cypress
using npm
, run:
npx cypress open
The command above will look for cypress executables for a version that is installed for the current project.
Otherwise, if you have installed cypress
using yarn
, then run:
yarn run cypress open
If cypress open
executes successfully, it would open a electron window. If you are setting it up for the first time, it would guide you to set it up as per your needs
Running Cypress headless
The previous section had commands to run cypress using electron UI, which will also open a browser and visually show you what is happening. However, if you are more interested in running it headless, that can also be done. To run Cypress headless, one shall run:
npx cypress run
If you are using yarn, you shall run:
yarn cypress run
But wait, this also has the option to run cypress in the browser visually and see your tests running. To do this just pass the flag --browser=<BROWSER_NAME_OR_PATH>
. Below is the list of all options available for the run
command
options
Option | Description |
---|---|
–browser, -b | Run Cypress in the browser with the given name. If a filesystem path is supplied, Cypress will attempt to use the browser at that path. |
–ci-build-id | Specify a unique identifier for a run to enable grouping or parallelization. |
–component | Run component tests |
–config, -c | Specify configuration |
–config-file, -C | Specify configuration file |
–e2e | Run end to end tests (default) |
–env, -e | Specify environment variables |
–group | Group recorded tests together under a single run |
–headed | Displays the browser instead of running headlessly |
–headless | Hide the browser instead of running headed (default during cypress run) |
–help, -h | Output usage information |
–key, -k | Specify your secret record key |
–no-exit | Keep Cypress open after tests in a spec file run |
–parallel | Run recorded specs in parallel across multiple machines |
–port,-p | Override default port |
–project, -P | Path to a specific project |
–quiet, -q | If passed, Cypress output will not be printed to stdout. Only output from the configured Mocha reporter will print. |
–record | Whether to record the test run |
–reporter, -r | Specify a Mocha reporter |
–reporter-options, -o | Specify Mocha reporter options |
–spec, -s | Specify the spec files to run |
–tag, -t | Identify a run with a tag or tags |
How to write Cypress test
We will cover how to write tests using cypress in detail in an article later, but just to give you a glimpse, below is an example, followed by code dissection
describe( "Twitter follow link", () => {
context( "https://www.example.com", () => {
beforeEach( () => {
cy.clock();
cy.visit( "https://www.example.com", {
onBeforeLoad: ( contentWindow ) => {
// contextWindow is a window object of browser page being visited
// Here one should write steps to be taken before onLoad event is fired
},
onLoad: ( window ) => {
// code here is executed when onLoad event of window is fired.
// it can be used for variety of thing i.e stubbing
});
})
it( "should click on follow button for twitter", () => {
cy.get( ".footer-block .fa-twitter" )
.click()
.tick(1000)
.window().then( ( win ) => {
expect("https://twitter.com/user").to.be.called
})
});
});
})
Code Dissection
If you had ever worked with RSpec, Jasmine, or Mocha; you already understand most of the code above. The describe
describes what the test is about. context
sets the context of the block of test(s), followed by it
. beforeEach
is a block that is (re)run before every it
block runs. There are other hooks available (i.e beforeAll
). Cypress engine is denoted by cy
object and it represents the entire environment of the test being run, environment variables, and exposes cypress API. If you see the following snippet from the example code above
cy.get( ".footer-block .fa-twitter" )
.click()
.tick(1000)
.window().then( ( win ) => {
expect("https://twitter.com/user").to.be.called
})
cy.get
takes CSS selectors or aliases to find HTML elements within the current window
object. When found click
it and then wait for 1000 ms before executing the next command in the chain. In the snippet above it waits for 1000 ms and then expect window
object must have called URL as passed to expect
Conclusion
Cypress has a vast API to control and automate browser functions, automate a task that we expect the user to perform, and compare results with our expectations.
Some of the advanced features of Cypress like playback video, time travel, and screenshots are paid features as they use Cypress Cloud Infrastructure.
About The Author
I am Pankaj Baagwan, a System Design Architect. A Computer Scientist by heart, process enthusiast, and open source author/contributor/writer. Advocates Karma. Love working with cutting edge, fascinating, open source technologies.
To consult Pankaj Bagwan on System Design, Cyber Security and Application Development, SEO and SMO, please reach out at me[at]bagwanpankaj[dot]com
For promotion/advertisement of your services and products on this blog, please reach out at me[at]bagwanpankaj[dot]com
Stay tuned <3. Signing off for RAAM