Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Table of Contents
minLevel1
maxLevel6
outlinefalse
styledecimal
typelist
printabletrue

Introduction

Why use Cypress?

  • Cypress allows us to write the following tests, while giving developers access to its interactive GUI

    • End-to-end tests

    • Component tests

    • Integration tests

    • Unit tests

  • Grab a coffee while you go through the features of Cypress.

Setup and Installation

Installation Steps

Expand
titleRun the following command in your terminal

npm install cypress

Expand
titleCreate and setup the dev config file
  • Create a dev.config.js file in the root directory of your local application and paste in the following content

  • Code Block
    const { defineConfig } = require('cypress');
    
    module.exports = defineConfig({
      e2e: {
        baseUrl: 'http://localhost:3000',
        excludeSpecPattern: '**/examples/*',
        screenshotOnRunFailure: false,
        //  supportFile: false,
      },
      viewportWidth: 1920,
      viewportHeight: 1080,
    
      component: {
        devServer: {
          framework: 'create-react-app',
          bundler: 'webpack',
        },
        screenshotOnRunFailure: false,
        env: {
          REACT_APP_MAPBOX_API_KEY: 'pk.eyJ1IjoibWlrYWhwaW5lZ2FyIiwiYSI6ImNseHZ2NndjZDJrejMycXB4dWtlamo2eWYifQ.29yeP8CgZpO98jyzxYxU4Q',
        },
      },
    });
    
Expand
titleTo open Cypress, run the following command

npx cypress open

Expand
titleFollow these steps in the cypress GUI
  1. Check for a new cypress window popup

  2. Select component testing

  3. For the Project Setup screen, do not change the detected framework (should be create react app) and select Next Step.

  4. Install all the dev dependencies (should be already installed, if not just npm install all the required dependencies) and select continue

  5. Next screen should show all the Configuration files, select continue

  6. Choose chrome as the browser and Start Component Testing in Chrome

Note

Check VSCODE for the project directory, you should see a new cypress folder created in the root folder. If not then the installation was not correct.

Expand
titlePost Installation
Note

use the command npx cypress open --config-file=dev.config.js in the dev environment to open the GUI instead of npx cypress open as not specifying the config file will point the config file to the default cypress.config.js file

1. Click on one of the test files in the Specs tab to see all the tests present

Dev Tests

While on development environment, check if you have the following file setup in the root folder of your local application (refer to the below image)

...

Common config changes

Put such changes like the viewport height/width settings, etc. directly in the defineConfig object.

E2E testing config changes

Put changes specific to E2E testing the e2e object. Following are the current e2e configs:

Code Block
languagejs
e2e: {
    baseUrl: 'http://localhost:3000', // base url for e2e testing
    excludeSpecPattern: '**/examples/*', // used to exclude tests whose names are filtered by the regex
    screenshotOnRunFailure: false, // if true a screenshot folder will be included with all the screen snippets when your tests fail
  },

Component testing config changes

Put changes specific to E2E testing the e2e object. Following are the current e2e configs:

Code Block
languagejs
component: {
    devServer: {
      framework: 'create-react-app',
      bundler: 'webpack',
    },
    screenshotOnRunFailure: false,
    // Defines environment variables for the component tests
    env: {
      REACT_APP_MAPBOX_API_KEY: 'apiKey',
    },
  },
Info

For customizing the configuration refer the following:
Cypress Doc link to Configuration File

Writing Tests

Testing Structure

Use the following structure for your test (spec) files:

  • Describe Blocks: Group related tests.

  • It Blocks: Define individual test cases.

  • Assertions: Validate expected outcomes.

For example,

Code Block
languagejs
describe('My React App', () => {
  it('should display the correct title', () => {
    cy.visit('/');
    cy.title().should('include', 'React App');
  });
});

Selectors and Best Practices

  • Use Data Attributes: Prefer data attributes (data-cy) for selecting elements.

  • Avoid Complex Selectors: Use simple selectors to avoid brittle tests.

Custom Cypress Commands

Use the cypress/support/< e2e/component >.js file to write custom commands for either e2e or component testing.
For example to avoid writing repetitive code to assert an element by id use the custom created command cy.assertByTestId

Code Block
languagejs
// code for adding a custom Cypress command
// @Params: [test-id]: string
// usecase: cy.assertByTestId("<test-id>");
// result: gives assertion for element existance
 
Cypress.Commands.add('assertByTestId', (testId) => {
  cy.get(`[data-cy=${testId}]`).should('exist');
});

Running Tests

  • Open tests in GUI by using the command

  • Code Block
    languagebash
    npx cypress open --config-file={env}.config.js
  • To open tests in headless mode (run in terminal without the GUI) run the following command

  • Code Block
    languagebash
    npx cypress run --config-file dev.config.js // runs e2e tests
    npx cypress run --component --config-file=dev.config.js // runs component tests

Debugging and Troubleshooting

  • Use cy.debug(): To pause and inspect the state.

  • View Cypress Logs: Check the logs in the Cypress Test Runner for errors and issues.

  • Check Network Requests: Use Cypress commands like cy.intercept() to monitor network requests.

Code Block
cy.intercept('GET', '/api/data', { fixture: 'data.json' }).as('getData');

Best Practices

  • Keep Tests Independent: Ensure each test runs in isolation.

  • Use Fixtures for Test Data: Load static data from files. Avoid making API calls from tests, as this will additional load on the servers. Use cy.intercept to intercept any type of HTTP call and send back dummy data.

  • Clean Up: Use hooks like beforeEach and afterEach to set up and tear down test states.

  • Write Descriptive Tests: Use clear and descriptive names for test cases and assertions. Begin all test descriptions with should.

  • Custom Commands: For repeated DOM queries, use aliases to make tests more readable.

  • BeforeEach: Use before each for all the repetitive commands within a describe block that is common to all the it blocks

  • Only assertions in It Blocks: Goal is to keep the It blocks as lean as possible, hence, avoid writing anything other than state management blocks and assertions in the It Blocks. Use the describe block to write all the component mounting and data initialization logic.

References