Paul Cowan Contract software developer

Cypress.io: The Selenium killer

7 min read 2130

Introduction

Before I start, I want to emphasize that this post is not about one particular project or any automation testers that I have worked with. I have seen this behavior in three recent projects, and nearly every automation tester that I have worked with has busted a gut to make this faulty machine work.

I am fairly sure that a memo has gone out to every contract that I have worked on recently stipulating that a million automation tests are required to guarantee success. We must not stop to question the worth of these tests. We must protect them like our children.

These tests must be written in selenium despite nearly everyone having a pretty grim experience due to the inherent known issues that I will state later.

Selenium tests are insanely challenging to write, but we won’t let that hold us back, and instead, we will get our testers who have maybe come into programming late or are new to development, and we will get these less experienced developers to write these difficult tests.

Selenium tests might be difficult to write, but they are straightforward to copy and paste, which will, of course, lead to all sorts of problems.

We often hear, “If it moves, write a selenium test for it”. Automation tests must be written for the API, the frontend, the backend, the middle-end, the happy path, the sad path, the upside-down path, etc.

We won’t have any time for manual testing, how could we? We have all these flakey selenium tests to write and maintain. We are already late for this sprint, and every story must have an automation test.

After a year or so and an insanely long build, we will decide that this was a bit silly and delete them all or, worse, start again.

Why does everyone still use Selenium despite the inherent problems?

I think I would be closer to understanding the true nature of our existence if I could answer the above question but joking aside, why is the use of selenium so widespread? It does stagger me, but here are a few suggestions:

To be fair, the sudden surge of writing a million acceptance tests is not selenium’s fault. For my money, the correct number of automation tests is one happy path test, no sad paths or upside-down paths. This one test is a smoke test to ensure that our system is open for business.

Unit tests and integration tests are cheaper to run, implement and maintain and should be the bulk of our tests, has everyone forgotten about the test pyramid?

Selenium is not fit for purpose and here is why

The problems with selenium can be expressed in one word, timing.

Before we can even start writing code to assert that our test is correct, we need to ensure that whatever elements we need to interact with are visible and are in a state to accept simulated input. Remote APIs calls will need to have resolved, animations and spinners need to have concluded. The dynamic content that now makes up the majority of our apps will need to have finished rendering from the currently retrieved data of the API calls.

So what do we do while this macabre pantomime of asynchronicity is occurring? How do we stop our tests from just finishing or bottoming out because a particular text input is disabled until an API call has finished or a beautiful SVG spinner overlay has put a veil of darkness over our virtual world?

In layman’s terms, we wait for the HTML elements to be in a ready state, in selenium speak, we write many custom waitForXXXXX code helpers, e.g.

waitForTheFullMoonAndTheWereWolvesHaveFinishedEating or more realistically…

wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@id='text3']")));

One of the worst crimes to commit is to use Thread.sleep. This is a heinous crime where a random number is plucked from thin air and used as a wild guess for when we think the UI is in a ready state. Please, never do this.

Below are my all-time favorite selenium exceptions that I have found while wading through a CI build report:

  • NoSuchElementException – move along, you’ll not find your input here
  • ElementNotVisibleException – this cheeky scamp means you are tantalizingly close but not close enough, it is in the DOM, but you can’t do a single thing with it
  • StaleElementReferenceException – the element has finished work for the day and gone to the pub. Please try again tomorrow
  • TimeoutException – you could wait until the end of time and whatever you are trying to do is just not going to happen. You just rolled a seven

Behold the flake

One of the most soul-destroying moments that I have experienced is having a build fail due to a failing automation test only for it to magically pass by just rerunning the build again. This phenomenon or zombie automation test is often referred to as a flake. The main problem with the flake is that it is non-deterministic which means that a test can exhibit different behavior when executed with the same inputs at different times. You can watch the confidence in your regression test suite go up in smoke as the number of non-deterministic tests rises.

A flakey test is more than likely down to timing, latency and the macabre opera of asynchronicity that we are trying to tame with our Thread.sleep and waitForAHero helpers that we need to keep writing to try and keep sane.

Just think how much easier this would be if we could somehow make all this asynchronous programming go away and if our world started to behave linearly or synchronously. What a natural world to test we would have.

Cypress.io sets out to do just that.

Cypress.io – The ghost in the machine

One of the main differences between cypress.io and selenium is that selenium executes in a process outside of the browser or device we are testing. Cypress executes in the browser and in the same run loop as the device under test.

Cypress executes the vast majority of its commands inside the browser, so there is no network lag. Commands run and drive your application as fast as its capable of rendering. To deal with modern JavaScript frameworks with complex UI’s, you use assertions to tell Cypress what the desired state of your application is.

Cypress will automatically wait for your application to reach this state before moving on. You are completely insulated from fussing with manual waits or retries. Cypress automatically waits for elements to exist and will never yield you stale elements that have been detached from the DOM.

This is the main take away, and cypress has eliminated the main problem with selenium by executing in the same run loop as the device. Cypress takes care of waiting for DOM elements to appear. I repeat, Cypress takes care of all this waiting business. No Thread.sleep, no waitForTheMoon helper. Don’t you see what this means?

To know how good this is, you have to have experienced the pain.

Below are a few examples of cypress tests. One thing synonymous by their absence is any timing or obscene waitFor helpers:

context("Login", () => {
  beforeEach(() => {
    cy.visit("localhost:8080/login");
  });

  it("can find and type in email", () => {
    cy.get("#email")
      .type("fake@email.com")
      .should("have.value", "fake@email.com");
  });

  it("can find and type in password", () => {
    cy.get("#password")
      .type("fakepassword")
      .should("have.value", "fakepassword");
  });

  it("will fail when type invalid user credentials", () => {
    cy.get("#email").type("fake@email.com");

    cy.get("#password").type("fakepassword");

    cy.get("input[type=submit]").click();

    cy.get("#login-message").should("have.text", "Login failed");
  });
});

I like these tests; they clearly state their purpose and are not obfuscated by code that makes up for the limitations of the platform.

Below are some tests I wrote to run the axe accessibility tool through cypress:

import { AxeConfig } from "../support/axeConfig";

describe("Axe violations", () => {
  beforeEach(() => {
    cy.visit("/");
    cy.injectAxe();
  });

  it("home page should have no axe violations", () => {
    cy.configureAxe(AxeConfig);
    cy.checkA11yAndReportViolations();
  });
});

And here is a similar test using webdriver:

// in e2e/home.test.js
import assert from 'assert';
import { By, until } from 'selenium-webdriver';
import {
    getDriver,
    analyzeAccessibility,
} from './helpers';

describe('Home page', () => {
    let driver;

    before(() => {
        driver = getDriver();
    });

    it('has no accessibility issues', async () => {
        await driver.get(`http://localhost:3000`);

        // The dreaded wait until.  Abandon hope
        await driver.wait(until.elementLocated(By.css('h1')));

        const results = await analyzeAccessibility();
        assert.equal(results.violations.length, 0);
    });
});

The main striking difference and the worrying thing to me is the latency, and there are two await calls and the dreaded wait(until.elementLocated). This is a simple test, but the more interactions you have, the more waitFor helpers you will need, and the flakiness starts spreading.

JavaScript all the way down

Cypress is clearly aimed at the frontend developer, installing cypress is a breeze and performed via your favorite package manager choice of npm or yarn.

npm install cypress --save-dev

It really could not be any easier. Compare that with downloading the chrome webdriver and friends in the world of selenium.

There is no multi-language support like selenium. You can have any programming language you like as long as it is JavaScript or TypeScript.

Cypress cons

Of course, there are drawbacks, and some of them are notable so it would be remiss of me not to list these.

  • Cypress is relatively new, and it does not have the vast community that selenium does
  • No cross-browser testing, this is huge and will cause less adoption until it can be cured
  • As stated earlier, it’s JavaScript or bust. You won’t write cypress tests in the tired old static languages of C# and java
  • Because it runs inside the browser, you won’t be able to support multiple tabs
  • There is no cross-browser support other than Chrome and Electron
  • At this time of writing, there is no shadow DOM support

The above items are, in some cases, insurmountable and will not be overcome.

Will Cypress replace Selenium?

As much as I would like to say yes, I have my doubts. There is an army of automation testers who have not known any other world than selenium, and it may be difficult to move away from soon.

Testing is just the beginning – ensure passed tests mean happy users

While Cypress introduces a compelling new testing framework, it’s important to take testing one step further. LogRocket monitors the entire client-side experience of your application and automatically surfaces any issues (especially those which tests might have missed). To gain valuable insight into production environments with frontend monitoring, try LogRocket. https://logrocket.com/signup/

LogRocket is like a DVR for web apps, recording literally everything that happens on your site. Instead of guessing why problems happen, you can aggregate and report on performance issues to quickly understand the root cause.

LogRocket instruments your app to record requests/responses with headers + bodies along with contextual information about the user to get a full picture of an issue. It also records the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page apps.

Make performance a priority – .

Conclusion

As I stated at the start of this article, my experience of automation testing is not a good one where a lot of money, time and pain are spent keeping thousands of hard to maintain tests afloat for not great payout. Automation testing has only ever guaranteed a long CI build in my experience.

We, as developers, need to be better at automation testing. We need to write fewer tests that do more and are useful. We’ve left some of the most difficult code to write to some of the least experienced developers. We’ve made manual testing seem outdated when, for my money, this is still where the real bugs are found.

We need to be sensible about what automation testing can achieve.

Cypress is great because it makes thing synchronous, this eliminates a whole world of pain, and for this, I am firmly on board. This, however, is not the green light to write thousands of cypress tests. The bulk of our tests are unit tests with a layer of integration tests before we get to a few happy path automation tests.

This, of course, is far too sensible a strategy ever to happen.

Plug: , a DVR for web apps

LogRocket is a frontend application monitoring solution that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.

In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page apps.

.
Paul Cowan Contract software developer

27 Replies to “Cypress.io: The Selenium killer”

  1. Write Selenium tests properly — with a proper class for pages that can encapsulate most of the complexities, and then additional tests become a breeze, fragility addressed in one place. Use the object oriented properties of those “old” enterprise languages. The author lost me anyway by saying “only test the happy path.” If you believe in a world where errors never happen, and want to irritate your customers who hit them even more, then go ahead and serve up broken web pages. I will stick with a well-tested system.

    1. Hi Erica,

      when I said only test the happy path, I meant only write acceptance tests for the happy path. The vast majority of our tests should be fine grained inexpensive unit tests with a layer of integration tests. Acceptance tests with selenium are too brittle and too expensive to maintain.

      1. The problem is brittle tests, not their usefulness. I assure you that testing of user experience during error handling matters. Other types of tests, while also important, are not enough.

        Fix your brittle tests — write a proper Selenium Page, encapsulate common user functions, and see how easy it is to write robust tests.

  2. Cypress.io. Just what Selenium used to be, like 15 year ago: A sandbox contained JavaScript library, embedded in your page. Now,w use Webdriver/Wire Protocol technology.

    No multi-browser testing, regardless of how much HTML and JavaScript have evolved, still ends on products that work on Chrome but not on Firefox. I have seen this happening regularly for the last 20 years.

  3. Well written but my biggest complaint is that you make judgement with your title but don’t really make that point. It should be a question.

    Cypress has its uses but I don’t think it’s going to be the tool to end all tools, specifically selenium. Selenium written with custom attributes and proper encapsulated classes be they page level or component level can be a very effective and valuable tool still.

    Cypress is doing some sort of waiting, it’s just not explicitly done by the client wiring up the tests. What does Cypress do if it truly can’t find the element you are looking for? It probably waits up to a certain time and fails.

  4. I think that you didn’t understood the author.
    “Only test the happy path” – means that UI should be automated as less as it could. Much more to be covered in unit and integration tests, and then just automate the happy path with UI. I agree with this part.

  5. I agree with the other commenter. Use page objects and proper wait logic and selenium isn’t that difficult. This article also left out a very big concern of mine for Cypress. Cypress uses semantic click and keystroke events through the DOM API, and doesn’t actually interact with the UI itself. For a quality acceptance test Cypress won’t work due to this constraint. Cypress is great for a front end developer integration test, but I cannot see it’s place for a quality group.

  6. Hi Nick, I think wait logic is a bit of an oxymoron here. Selenium executes at break neck speed and not anything remotely like a user. you simply have to add lots of waitForXXX helpers. network latency in the CI environment quickly lead to non deterministic tests. you are left with a bunch of brittle and hard to maintain tests that make change really difficult, hence my call for 1 happy path acceptance test is sensible but I can see rushing to call this heresy by people who make a living adding a mountain of these tests.

  7. I think you are blaming selenium for developers bad practices in most cases. The waits are there for a good reasons. Im sure there is a thread.sleep buried in your dlls.

  8. The title should be a question mark. The content has not convinced me that it is a selenium killer.

  9. From my point of view this article makes the wrong assumption from the start. It is not Selenium’s problems if tests are flaky – you need a good test framework to handle this well. Also he totally dismisses the point that Webdriver is now a W3C standard that vendors have to follow. Of course, if you have to test in Chrome only, it will be much faster as it is running inside of it. The same applies if you use an ios or android specific test framework as opposed to a generic one for all.

  10. How does that “logon error” test work? Clicking the submit button is likely to kick off some asynç work, but you check for the error message immediately after clicking it.

  11. That’s a pretty substantial list of drawbacks and the only pro that I take away from this article is that I don’t have to explicitly handle any waiting in my code. I’d gladly add the one-liner wait statements here and there as a tradeoff for that laundry list of drawbacks.

  12. Cypress waits for a page load event before firing the next enqueued command. In this case either a toast message is displayed and cypress will find it or the page would attempt to log in and be redirected back to a failed login page. He kind of glossed over how being in the same run-loop as the application gives Cypress access to the network. Thus it can ensure (unless your app doesn’t send a page load event) in most cases that next command waits for the proper state.

  13. Also in defense of a different way: POM abstraction in most large case test suites tends to be a detriment for upkeep and onboarding. I can’t tell you how many times an entire suite is thrown away because reverse engineering it can be maddening for a new SDET. So to those who think page objects solves the selenium problem are missing the point. Cypress stresses quick test creation and state management + easy ci/cd setup.

  14. Cypress.io is not a replacement or killer for Selenium WebDriver it’s just another cool and trending tool to use, which looks awesome and really have a lot of cool features. One of the big problems of cypress is inability to do cross browser testing, so currently only chrome browser and electron framework are supported. Selenium WebDriver on the other hand is a W3C standard (https://www.w3.org/TR/webdriver1/) and all the major web-browsers creators supporting it by developing dedicated WebDrivers which are W3C standard compliant.
    Now cypress would like to support all the other browsers in the future, and they figured out that to do this they will need to use the same dedicated WebDrivers which Selenium is currently using (https://github.com/cypress-io/cypress/issues/310).

  15. However, cypress has lots of limitations, for instance you can’t upload or download files, no multiple tabs or iframes support. While Cypress is a good tool for components testing, for general end 2 end tests I prefer Puppeteer from Google Chrome. I also use CodeceptJS which has a very simple syntax and brings cypress-like experience to Puppteer.

  16. Cypress does have a lot of limitations, however some of which you mentioned aren’t or can be circumvented at least.

    You can upload files by trigger a drop event on the desired input field
    (https://github.com/cypress-io/cypress/issues/170#issuecomment-311196166)

    And you can download files and make assertions on them
    You can catch the name of the downloaded file by catching the event
    https://docs.cypress.io/api/events/catalog-of-events.html#Event-Types

    And since cypress runs on node you can read directories and make assertions on the existence of the downloaded file in the appropriate folder.

    Imo cypress won’t replace selenium, but it is an easily graspable and implementable tool which can ease development for the developers, since they can debug the app during the tests

  17. The lack of Cross Browser support is a deal killer, and will also be a Cypress killer if they don;t figure it out.

  18. I agree with this. In my current project first end to end test was developed in 2 hours by newly joined SDET. With existing POM selenium framework it would have been min 2 days to understand the framework then start using existing “reusable” methods to develop first script.

  19. Cypress is not a Selenium killer, rather it adds to the stack of tools to use. Cypress is very good at quickly testing components on a page and proving that they work. You can then use Selenium to test the e2e flows through the web app hitting the top 3-5 flows that users take. With less flows through the app the Selenium framework can be smaller and therefore less complicated. If there is a failure you know it is to do with the component integration or (if you are doing cross-browser testing) the browser’s implementation as the cypress tests have already tested the logic.

Leave a Reply