Ahmet Kapusuz

Testing React application with Cypress

Cypress is a tool that let you write and run your integration tests fast and easy. To learn more about Cypress, you can visit the website or github repo of Cypress.

I will demonstrate a simple test on my simple Calculator application. You can clone the sample app from this repository.

First, navigate into the application folder and add cypress as a dev dependency with below command.

yarn add --dev cypress

You can see that cypress is added into your package.json file as below:

"devDependencies": {
  "cypress": "^3.0.2"
}

To start cypress, you should run the command below when you’re in the application root folder.

yarn run cypress open

This will open cypress window and also add example tests folder into your project.

cypress 1

Now we can start writing our integration tests.

Create a new folder and name it as calculator-app under cypress->integration folder. And create a new file named calculator_app.spec.js, this is the file we’re going to write our tests.

If you open Calculator.js file and look at the render function, you can see that I’ve added an extra property to each element, data-cy. This is added to find elements easily and doesn’t effect the changes on classes or dom structure. This is defined as a best practice by the Cypress team, you can see other best practices from this tutorial.

Let’s add our first test, this calculator should be able to add two numbers. To test this we will add the code block below into calculator_app.spec.js file.

describe('calculator', function() {
  beforeEach(function() {
    cy.visit('http://localhost:3000');
  });

  it('should add two numbers', function() {
    cy.get('[data-cy=button1]').click();
    cy.get('[data-cy=buttonSum]').click();
    cy.get('[data-cy=button2]').click();
    cy.get('[data-cy=buttonEquals]').click();
    cy.get('[data-cy=result]').should('have.value', '3');
  });

  afterEach(function() {
    cy.get('[data-cy=buttonClear]').click();
  });
});

This code simply visits http://localhost:3000 page, which our application runs, then clicks some buttons, then checks if the result value is correct. And after each tests clicks clear button to remove last value on the input field.

To run this test, first you should start the application. So, navigate into the application folder and run the command below:

yarn start

Then, navigate into application folder and run the command below to start your tests;

yarn run cypress open

This will open cypress window and then you can click calculator_app.spec.js to run your test. You should see a similar window below, which displays your test has run and completed successfully.

cypress 2

Similarly, you can write your tests for other operations.

You can clone full application with tests from this repository.


Ahmet Kapusuz

Written by Ahmet Kapusuz who lives and works in Amsterdam as a Software Engineer.