Components are reusable bits of code that, most of the time, work and function independently. If you want to be confident that components are working properly, you need to test them. Conveniently, Cypress.io has designed their testing framework to include component testing. This tutorial illustrates the differences between end-to-end (E2E) and component testing, and what to consider when using these methods. Then, you will learn how to use Cypress for component testing.

Prerequisites

To follow along easily, you will need:

  1. Node.js installed
  2. CircleCI account
  3. GitHub account and an understanding of Git
  4. Sound knowledge of JavaScript and React
  5. Understanding of how pipelines work
  6. A clone of the demo React app

Our tutorials are platform-agnostic, but use CircleCI as an example. If you don’t have a CircleCI account, sign up for a free one here.

Note: The React component has been developed and can be found in the cloned repository under src/components/App.js. To keep things simple, the focus of this tutorial will be on testing the already developed React component.

In the next section, we will look at component testing and how it compares to end-to-end testing.

What is component testing?

A component is a distinguishable part of a software program. Forms, calls to action, and site searches are examples of web application components. Web components can be anything from a simple call to action button to a full registration form submission.

Component testing is also known as program or module testing. The process consists of independently verifying and validating the functionality, performance, and compliance to requirements of a specific component from the main application. This testing is limited to that particular component and is made simple by the nature of the easily testable features.

Component testing vs end-to-end testing

E2E tests determine whether the flow of an application from start to finish proceeds as expected. E2E tests include testing integrations with third-party APIs and services. Critical functionality gets tested throughout the application. Cypress uses a browser to run end-to-end tests in the same way that users interact with an application. Basic end-to-end testing for an application might include user registration, confirmation email, login, profile update, and logout.

End-to-end tests are more comprehensive, slower, and more prone to flakiness than component tests. Component tests are specialized, quick, and reliable. Because of the scope, end-to-end testing often requires a complex set-up phase. No complicated configurations are needed for component tests.

End-to-end tests in Cypress can be written by developers, specialized testing engineers, or a quality assurance team. Usually, the component developers themselves write component tests. Developers can easily verify a component’s required functionality while building it. As you are writing the actual component tests later in the tutorial, you will notice that the initialization command in Cypress end-to-end tests is cy.visit(url). Component tests use cy.mount(<MyComponent />). A well-tested app includes both end-to-end and component tests, with each set of tests specializing in the tasks they perform best.

Note: A test is considered “flaky” when it passes and fails without any changes to the code or the test itself. This signifies either an unstable system or poorly designed/written tests. Learn more in How to reduce flaky test failures.

Advantages of component testing include:

  • Detects module flaws
  • Components are tested on their own, not as part of the whole application
  • Limited scope makes them quick and dependable
  • Reduces development time
  • Easy to set up specific scenarios
  • No external system needed

To learn more about comparing testing methods, visit Cypress Testing Types.

Now that you understand Cypress component testing, the next sections will show you how to configure Cypress in an application, how to write tests, and how to run them.

Using Cypress for component testing

To test a React application using Cypress E2E tests, you would run the app on a local development server while Cypress runs in a separate terminal. Cypress visits your application using the command cy.visit(url) and runs assertions on the loaded page.

The latest versions of Cypress include a built-in development server, eliminating the need for a local development server when performing component tests. The built-in server in Cypress is in charge of mounting and rendering the component in the browser. It only mounts and renders the component separate from the main application.

Testing in Cypress overview

This illustration shows that Cypress runs component tests in this order:

  • Mounts the component with the cy.mount() command
  • Renders the component
  • Uses Cypress commands to test component attributes

A failure at a specified point causes the test to fail.

Writing component tests

This section details how to configure Cypress and write tests for the cloned newsletter subscription component. Before you can write component tests, you need to install Cypress and integrate it with React.

To install Cypress, enter:

npm install cypress --save-dev

This installs Cypress locally as a dev dependency for the project.

To open the application, enter:

npx cypress open

This command opens the Cypress launchpad.

Select Component Testing

Select testing option

Confirm the frontend framework and bundler, and click Next Step.

Select frontend framework

The development dependencies are already installed. Go to the next step by clicking Continue.

Install dev dependencies

Cypress then generates configuration files for the testing type you selected. Click the Continue button.

Cypress generated configuration files: .zoomable }

Click your preferred browser to continue.

Choose a browser

You want to start writing your tests from the ground up, so select Create new empty spec.

Give the spec a name, then click the Create Spec button.

Path to spec

Now you have a specification file that includes sample code. Run the file.

Run spec

Now you can start creating tests for your newsletter subscription form. The test should verify that these actions happen:

  • The component is installed correctly
  • There is a placeholder in the input field
  • A success message is returned after a subscription

In the spec file you just created, replace the generated code with this:

// cypress/component/NewsLetterSubscription.cy.js file

import App from "../.././src/components/App";

describe("NewsLetterSubscription.cy.js", () => {
  describe("NewsLetterSubscription.cy.js", () => {
    it("Check input field for placeholder", () => {
      cy.mount(<App />); // mount the component
      cy.get("input").should("have.attr", "placeholder", "Subscribe to our newsletter"); // check the placeholder in the input field
    });
    it("test newsletter subscription", () => {
      cy.mount(<App />); // mount the component
      cy.get('[data-test="email-input"]').type("test@gmail.com"); // Type email
      cy.get('[data-test="submit-button"]').click(); // Click on submit button
      cy.get('[data-test="success-message"]')
        .should("exist")
        .contains("Thank you for subscribing to our newsletter"); // Check if success message is displayed
    });
  });
});

This test suite first mounts the component with the cy.mount() command. It then checks to see if the input field has a placeholder with some text using the cy.get() function.

When you enter an email address and click the subscribe button, a success message should be returned.

Go to the Cypress browser to make sure that the tests passed.

Passing tests

Congratulations, you have a tested React component! Your next step is to integrate your tests to a CI/CD pipeline. For that, you can use CircleCI.

Configuring CircleCI

To get started with CircleCI configuration, create a .circleci folder at the root of the project. Inside it, create a file named config.yml. To make configuration a bit easier, you can use CircleCI orbs.

Note: Before using the Cypress CircleCI orb in your project, from organization settings, allow the use of uncertified orbs. Settings -> Security -> Allow uncertified orbs.

Enter the following content into the config.yml file:

version: 2.1 # Use 2.1 to make use of orbs and other features
orbs: # An orb is a reusable package of CircleCI configuration that you may share
  # across projects, enabling you to create encapsulated, parameterized commands, jobs, and
  # executors that can be used across multiple projects.
  cypress: cypress-io/cypress@3.1.2
workflows: # Workflows are a declarative way to orchestrate jobs and their run order.
  build:
    jobs:
      - cypress/run: # Run the cypress/run job from the cypress orb
          cypress-command: npx cypress run --headless --component # Run the cypress run command in headless mode

Add the project to GitHub, then log into your CircleCI account.

Find the project in the list on the Project tab. Click Set Up Project.

Select a project

Enter main as the name of the GitHub branch containing your CircleCI configuration. Click Set Up Project.

CircleCI starts your pipeline, which will run the tests. After a few minutes, your tests should pass. Click on the green success badge to review the details.

Successful workflow

Great! You have successfully set up tests to run whenever you change the code.

Conclusion

In this post, you learned what component testing is, how it differs from E2E testing, and what its benefits are. You learned how to use Cypress for component testing, configure Cypress in a React project, test components in Cypress tests, and how to run the tests. You finished the project by setting up CircleCI to automatically execute your component tests. I hope you enjoyed reading this as much as I enjoyed creating it. Until next time, keep learning!


Waweru Mwaura is a software engineer and a life-long learner who specializes in quality engineering. He is an author at Packt and enjoys reading about engineering, finance, and technology. You can read more about him on his web profile.

Read more posts by Waweru Mwaura