Guide for Cypress Component Testing and its Implementation
Firstly, we will try to understand what component testing is. While testing a web application there are three types of testing which plays an important role in determining the performance of the application which are API testing, Component testing and End 2 End testing.
With the help of component testing we determine the behaviour of all the individual components which integrate to make one application. Here we make sure each component is working fine before integrating it with other components of the application, This testing is also known as module testing.
If we want to understand this in a simpler way, components or modules are like lego blocks individually; they look like just a block and when combined with other blocks they come up with a meaningful structure. But before combining them we need to test them thoroughly so that they can be used as the building block on a lego structure. In this article we will be covering differences between component and end to end testing, implementation of Component testing using javascript and react JS and finally benefits of Component testing
Why component testing?
Component testing is a type of unit testing where we test all the component codes in isolation. There are multiple benefits of doing this, it helps in identification of bugs early in the product development life cycle. Early detection helps in early fixing of bugs and makes it easier to pinpoint the actual reason inside the component. It helps in improving code quality, as while performing unit testing and writing unit test cases will help developers to follow high quality code and maintain best coding practice.
Overall Component testing will help in supporting refactoring, enhancing code reusability and improving code quality.
Component Testing Vs End to End testing
Primary difference between both types of testing is, in component testing a component is built using a server which is used for development instead of going through a complete website. Because of this we get fewer tests and fast results with very less dependency on infrastructural requirements. Whereas in end to end testing we need to go through the complete website and it has a good amount of dependency on infrastructure.
Cypress API for component testing helps developers in performing testing in the most approachable and efficient way.
How to perform Component testing using Cypress?
Mostly Cypress is used for End 2 End and UI testing but we can use cypress for component testing as well. Below are the steps which we need to perform while doing Component testing using Cypress automaton:
Step 1: Firstly we need to make sure Cypress is installed in our system and create a new project structure or use the already present project structure.
Step 2: Creating a specific Cypress test file for component testing, we will be placing this test file inside director “cypress/integration”. And we can name the test file as “component.spec.js”.
Step 3: Post above step we will be starting writing our first component test inside our test file. We will be writing Cypress test to target the component under test, we can use cypress commands to have interaction with component, like ‘cy.get()’ to select elements on component, ‘cy.click()’ to perform action on component under test and we use other commands to validate assertion the component.
Below is the example code 1:
// component.spec.js
describe('Component Test', () => {
it('should display the component', () => {
cy.visit('/path-to-your-component'); // Visit the component's URL
cy.get('.your-component-class').should('be.visible'); // Replace with your component's selector
});
it('should interact with the component', () => {
cy.visit('/path-to-your-component');
cy.get('.your-button-class').click(); // Click a button within your component
cy.get('.result').should('contain', 'Expected Result'); // Assert the expected result
});
});
example code 2:
// component.spec.js
describe('MyComponent', () => {
beforeEach(() => {
// Visit the page or component where your component is rendered
cy.visit('/path-to-component');
});
it('should display the component', () => {
// Use Cypress commands to interact with your component
cy.get('.my-component').should('exist');
});
it('should perform some actions', () => {
// Simulate user interactions
cy.get('.button').click();
// Assert the result of the interaction
cy.get('.result').should('contain', 'Expected Result');
});
});
Step 4: Perform execution of the cypress test which we wrote and perform analysis of test results, as a part of test results we can have all the required information like screenshot of recordings. We can perform integration of these tests with CI/CD as well, which will help in validating these components after every deployment and builds.
Cypress Component testing with React
For performing testing of React based applications first we need a framework in CRA (Create React app), then Cypress will automatically detect this framework.
Step 1: First we need to create an application in react, if it is not created already. We can use the Create React App (CRA) for doing this.
npx create-react-app my-cypress-app
cd my-cypress-app
Step 2: Perform Configurations on cypress for performing Component testing, As cypress have already predefined support for react we can use “@cypress/react” plugin for that. We need to configure our React application to work with it. Post that we can create “cypress.json” in project directory with below details:
{
"component": {
"componentFolder": "src",
"testFiles": "**/*.spec.{js,ts,jsx,tsx}",
"jsx": "automatic"
}
}
Here the Component folder provides the location where the react component is located, test files depict the pattern of the test file which we are going to use like ‘spec.js’, ‘spec.ts’ or ‘spec.jsx’.
Step 4: In this step we will start writing a component test for the module under test, if we are testing a module where we need to make sure buttons are working fine we will be writing a test script for that.
// Button.spec.js
import React from 'react';
import { mount } from '@cypress/react';
import Button from './Button';
describe('Button Component', () => {
it('renders correctly', () => {
mount(<Button label="Click me" />);
cy.get('button').should('contain', 'Click me');
});
it('handles click events', () => {
let clicked = false;
const handleClick = () => (clicked = true);
mount(<Button label="Click me" onClick={handleClick} />);
cy.get('button').click();
expect(clicked).to.be.true;
});
});
Step 5: Finally we will be running the test which we have written in step 4, for getting the desired results.
npx cypress open-ct
Benefits of Cypress for Component testing
There are various benefits of performing component testing using cypress few of them are, the test runner in cypress is web-based which helps developers or testers to test there component functionality, with functionality they can validate it visually as well and interact through it using test runner. Browser developer tools can be used by the user to perform inspect on DOM, they can play around with styles and perform debug operations as well.
Complete User interface which comes with cypress Component testing module is very user interactive and easy to use, developer or tester coming from any background can easily adapt and understand the functionality. Which can later help them in using the tool at its full capacity and get the best results of it.
Using Component testing which achieves a shift left approach in application development and testing, as bug identification can take place earlier. So overall bug fixing cost can be reduced considerably.
Conclusion
Component testing is one of the most important testing as the result which we get from it is bug free and can act as a good input for integration testing. Using Cypress it became achievable and easy to use, as we have separate options in parallel to End to end testing where we can define framework for component testing and use UI driven option to define test cases. We can go through the DOM structure, see the UI capability of developed components, perform UI interaction and try different styles. Overall it is very helpful for developers as they can do alot and the end result will be great after implementing these techniques.
Source: This blog was originally published at https://testgrid.io/blog/cypress-component-testing/
Subscribe to my newsletter
Read articles from Ronika Kashyap directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Ronika Kashyap
Ronika Kashyap
Experienced Software Tester with 7+ years of ensuring product excellence. Proficient in automation, API testing, and Agile. Achieved 30% test coverage increase. Dedicated to delivering top-notch software.