Published in


End-to-end testing with Cypress, Testing Library

Here’s the minimum you should know if you want to test web UIs with Cypress (an alternative to Selenium), a Node-based approach.

1. New project

In a new folder, run npm init and follow the steps (simply press Enter when in doubt).

My advice is to start a new git repository (git init) so you can always undo it if needed. Each step is a good moment to run a git commit. Start with this .gitignore file:


2. Adding Cypress

  1. Run the command: npm install cypress --save-dev
  2. At package.json, change the command (under "scripts") to run the tests to be: "test": "cypress run --browser chrome --headed"
  3. At the project’s root, create an empty file for Cypress configuration named cypress.json with the content: { "video": false }
  4. Now we need a dummy test just to prove everything’s fine so far. Create the folder structure cypress/integration with a file named amazonCart.js. The content should be:
describe('Amazon cart test', () => {
it('adds to cart', () => {

Now, run the tests with npm test (or just npm t). You should see: ✔ All specs passed!

3. Adding Testing Library

To me, the Testing Library is a must-have when testing web apps or websites. On one hand, it promotes the total decoupling of tests from HTML details like ids and classes (it’s an anti-pattern to add those only for the sake of testing). On the other hand, it helps in writing semantic HTML which benefits accessibility and SEO. If you can’t easily find something, how could users do it? How would a screen reader deal with lousy HTML? Built-in selectors find elements the way users do.

Let’s add the Cypress version of the Testing Library with npm install @testing-library/cypress --save-dev

Add this line to your project’s cypress/support/commands.js:

import '@testing-library/cypress/add-commands';

Let’s experiment with Cypress for Testing Library by changing cypress/integration/amazonCart.js:

describe('Amazon cart test', () => {
it('adds to cart', () => {
cy.findByRole('textbox', {name: /search/i})

findByRole is an example of the Testing Library. Since this textbox doesn’t have a label, we had to resort to the role approach. I recommend reading the official page about Testing Library queries.

Now, time to run the tests again with npm t and see the results:

✔ All specs passed!



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store