DEV Community

Diego Daniel
Diego Daniel

Posted on

How Cypress might be the easiest way to setup E2E tests for your web app

Yesterday, I discovered Cypress (repo), an all-in-one testing platform for frontend applications. It is an amazing tool that is both easy to use and effective.

How to setup cypress in your project

First, install the npm package

npm install --save-dev cypress
# Or
yarn add --dev cypress

Then, open it with

node_modules/.bin/cypress open

You be greeted with a window where you can run the example tests that show the features of cypress:

Then, you can start wrinting tests.

How to write tests

A simple login test can be written in 9 lines as:

describe('Log in', () => {
  it('should log in and redirect to home page', () => {
    cy.visit('http://localhost:3001/');
    cy.get('[data-testid=EmailInput]').type('user@email.com');
    cy.get('[data-testid=PasswordInput]').type('123');
    cy.get('[data-testid=SignInButton]').click();
    cy.url().should('match', /home$/);
  });
});
  • describe simple groups tests under a title, in this case 'Log in'
  • it defines a new test with a title, in this case 'should log in and redirect to home page'
  • cy.visit makes the cypress browser access our server login page
  • cy.get gets an HTML element on the page
  • cy.get(...).type types text on an element
  • cy.get(...).click clicks on the element (surprising, I know)
  • cy.url() allows to make assertions on the current url.

So basically, we access the login page, types an user email and password, clicks on the log in button, and checks to see we were redirected to the home page.

Finishing up

You could do the setup and have a working log in test in less than 15 minutes. That's the simplicity of cypress, and why you should at least consider using it to test your wep apps.

Don't forget to read the best practices page on their documentation, and watch the best practices talk video to learn more about the tool.

PS: If you're using Typescript, like me, this guide might save you a little bit of time to get TS to work with cypress.

Top comments (2)

Collapse
 
oaraujocesar profile image
César O. Araújo

Artigo muito legal, Diego! :)
Posta mais sobre Cypress!

Collapse
 
lockn profile image
Diego Daniel

Obrigado!
Eu ainda tô aprendendo, como disse eu descobri ele ontem :p

Mas com certeza vou fazer outros artigos rapinhos sobre outras features do Cypress (ele é muito satisfatório de se usar)