How to Test React using Cypress
By Priyanka Bhat, Community Contributor - February 6, 2023
Organizations are more keen on developing applications more rapidly, with fewer costs. To do so they are preferring modern web development frameworks, rather than building their own.
The web development framework has evolved a lot, the Javascript-based front-end frameworks are getting popular. The modern javascript web development frameworks are competing with each other by adding more features, making it easier to learn and code. Angular, Vue, Next, and React are such modern javascript frameworks that help in the rapid development of web applications.
Read More: Angular vs React vs Vue: Core Differences
On the other hand, test automation frameworks are also evolving to match up with the development. Modern tools such as Cypress, Playwright, NightwatchJS, and Puppeteer are getting popular over the old Selenium based framework.
- What is ReactJS?
- Why are React Applications so popular?
- Testing React Applications
- What is Cypress?
- Why use Cypress for testing react applications?
- How to test React applications using Cypress?
- Creating your first React Application Test with Cypress
- Execute Cypress React tests
- Component Testing in Cypress
- Cypress Testing Best Practices
What is ReactJS?
ReactJS (popularly known as React) is a web application framework. React is a javascript-based open-source framework and library developed by Facebook (Meta). It is used to develop frontend user interfaces quickly and efficiently with less code. React framework provides independent reusable components using which one can develop application-specific UI components, later these components are grouped together to make the entire user interface of the application.
Why are React Applications so popular?
Most organizations adopt the agile-driven development methodology where the application features are developed and delivered in an iterative approach, as mentioned earlier the react framework follows the component-driven approach the independent components can be built and tested. The react fits best in an agile environment and eventually helps in faster application delivery.
The ReactJS Stats
React on Github
- Used by: 13.1 Million
- Contributors: 1,598
- Stars: 200K
- Forks: 41.6K
ReactJS trend over Angular by Google Trends
ReactJS now has millions of users worldwide and is still counting. React is popular because of its frequent and stable releases, ease to use, ease of integration, and customization. React has become the first choice of many organizations.
Testing React Applications
Unlike old-style MVC applications the ReactJS application uses dynamic content loading, the tester may find difficulty in automating with an old age framework which was primarily designed for MVC and later enhanced to modern applications. However, modern testing tools like Cypress, and Playwright can automate ReactJS applications more easily without any hassle.
Read More: Playwright vs Cypress: A Comparison
What is Cypress?
Cypress is a Javascript-based open-source test automation tool, designed for modern web application automation testing. Cypress is popular due to its simplicity in nature, it shares some unique features like advanced debugging, automatic waiting, mocking network requests, etc.
Cypress supports many browsers like Chrome, Edge, Electron, and Firefox. The recent update shows that they are experimenting with Safari’s open-source version which is a WebKit browser. One of the major advantages of Cypress is Cypress runs in the same environment where your application runs so you can have control over your application during test execution.
Read More: How to run Cypress Tests on Firefox Browser
Why use Cypress for testing react applications?
React is a modern web application framework, unlike old-style MVC applications React uses a special mechanism to render DOM contents which makes several automation tools end up with flaky tests and adds more slowness during execution. Enhancing an old-age automation framework to support React is time-consuming and requires expert knowledge in programming language and architecture.
Cypress fits best in testing react-based applications as it knows how to manipulate modern DOM contents. Cypress comes with a completely different architecture in comparison with popular selenium-based frameworks. Using Cypress for your React application makes automation tests more stable, reliable, and effective.
How to test React applications using Cypress?
Cypress is an easy to use tool, setting up Cypress for react applications quicker and easier.
Pre-requisites:
- Download and Install NodeJS
- Download and Install VSCode (Optional and Recommended)
Step 1: Create package.json
Use the below command to create package.json
npm init
The package.json helps to track all installed dependencies and its version, with the advanced setup you can also configure the shortcuts for building and executing the command
Step 2: Install Cypress
Cypress is shipped as a NodeJS package, you can use the npm command to install the Cypress
npm install cypress --save-dev
The above command will install the cypress locally in your project folder.
Step 3: Open Cypress
When you install Cypress for the first time, cypress needs to create all required project folders and do the initial set up. Cypress open command does all these.
npx cypress open
Step 4: Configuring Cypress
Once you type the cypress open command, the Cypress window opens and asks you to choose a set of options, choose as per your project requirements below is the example.
Step 5: Choose the Test Type
The welcome window shows two different types of tests, End to End Testing and Component Testing in this case we are performing UI end-to-end testing so you can choose the test type as End to End Tests
Step 6: Review the Configuration File and continue
The Cypress window shows that there are a set of configuration files that Cypress will create by default, you can review the files and Click on Continue.
Step 7: Choose a browser
You can choose from the available browser, Cypress gathers information from all installed browsers in your System. If it supports the Browser type and browser version then it lists in the Choose a browser section. For simplicity, let’s choose Chrome browser and Click on Start End to end Testing using Chrome.
Step 8: Create First Spec window
Since you have created the fresh framework, you need to create the first spec, this also helps to verify if Cypress is installed correctly and able to run our automated tests.
- Click on Create a New Spec
- Enter any name (Example: react-demo.cy.js)
- Click on Okay, run the Spec
Note: By default, it adds the example test script, we can modify them later as per our use case or test scenario
Our Cypress framework is now configured!. Learn more about building your Cypress automation framework
Pro-Tip: For better accuracy, it is recommended to run React Cypress Tests on Real devices and browsers using BrowserStack Real Device Cloud. This will help you run tests under real user conditions for delivering a good user experience.
Run Cypress Tests on Real Devices
Let’s jump on to ReactJS testing.
Let’s take a simple scenario
- Navigate to https://reactjs.org/
- In the Demo Todo component add the todo item
- Validate the result if todo items are added correctly
Creating your first React Application Test with Cypress
As part of the setup you have already created one spec file which is react-demo.cy.js which is located in the cypress/e2e/ folder, Navigate to that folder and modify the code.
The “describe” block is a container of tests, you can think of the “describe” block as a test suite. Provide the relevant name to describe the block
In our example we are interacting with the to-do list, let’s change the “describe” block to “React todo example”
The “it” block contains actual test cases, individual test cases are placed inside it block, considering our use case let’s update it block as “Should add and verify todo list”
The “it” block contains the actual test script, so you need to add the cypress code inside the “it” block.
//react-demo.cy.js describe('React todo example', () => { it('Should add and verify todo list', () => { cy.visit('https://reactjs.org/'); cy.get('#new-todo').type("My first todo item"); cy.get('#new-todo').siblings('button').click(); cy.get('#new-todo').type("My second todo item"); cy.get('#new-todo').siblings('button').click(); cy.get('div[id = "todos-example"] >div >ul > li').eq(0).should('have.text', 'My first todo item') cy.get('div[id = "todos-example"] >div >ul > li').eq(1).should('have.text', 'My second todo item') }) }
Let’s understand the above example
- cy.visit() : The cy.visit() performs the navigation functions, as we have added value as https://reactjs.org/ it navigates to the web page.
- cy.get(): This cypress command find the element in the DOM tree, here we are giving the id selector which is #new-todo it finds the element.
- .type(): The type command is chained with cy.get() which means the cypress find the elements and type the specified text on it
- .click(): The click command is chained with cy.get() which means the cypress find the elements and clicks on it
- .should(): The .should() is an assertion it validates specified values, in our case we are validating text should be ‘My first todo item’
Execute Cypress React tests
Cypress react tests can be executed in two ways
- Using command line
- Using Cypress window user interface
Run Cypress Tests on Real Devices
Execute Cypress tests using the Command Line
Syntax:
npx cypress run --browser <browser_name> --spec <spec_file>
Example:
npx cypress run --browser chrome --spec './cypress/e2e/react-demo.cy.js'
Execute Cypress tests using the Cypress Window
- Enter the command npx cypress open
- Click on End to End testing
- Choose the browser and Start
- Click on the test name (example, react-demo.cy.js)
Output:Let’s take another example of React Calculator operation
- Navigate to https://ahfarmer.github.io/calculator/
- Perform addition operation on a calculator
- Enter 7 + 9
- Verify the Result should be 16
Source code
//react-demo.cy.js describe('React calculator example', () => { it('Should validate addition operation', () => { cy.visit('https://ahfarmer.github.io/calculator/'); cy.get('button').contains('7').click(); cy.get('button').contains(/^\+$/).click(); cy.get('button').contains('9').click(); cy.get('button').contains('=').click(); cy.get('div[class="component-display"]>div').should('have.text','16') }) })
In the above example, we are navigating to https://ahfarmer.github.io/calculator/ by using cy.visit(). Then using the cy.get() and cy.click() we are performing click actions on the calculator button. Using the .should() we are verifying the addition operation.
Now, we have two tests inside the react-todo.cy.js. Let’s execute and see the result
Component Testing in Cypress
Component testing helps to test individual component of application. This method makes the development faster and helps to develop individual bug free components. Unlike End to end testing the component testing focuses on smaller or group of features, the user journey is not tested rather the component functionality is validated against the requirements.
The Cypress 10 and above allows users to perform the component testing. The Cypress component testing article helps you to explore more.
Follow-up Read: How to migrate your Test Automation Suite to Cypress 10
Cypress Testing Best Practices
- Use programmatic login to take control of the application state
- Whenever possible use data-* attribute to select the elements
- If you want to verify the text on the application use the cy.contains()
- Use the beforeEach(), afterEach() block to add the shared code which is required for every test
- Cypress automatically waits for elements, do not add the waits unless it is required
- Use assertions for every test to mark the test as fail or pass
- Focus each test on a single scenario
The modern development framework helps to develop the application faster by using an agile environment, However, manual testing may cause a delay in the delivery of the application. The powerful development framework React and the powerful automation framework Cypress makes your application delivery smoother and faster.
However, based on the organization and client requirements the Cypress tool alone will not be enough for testing and we might have to do the product release without performing the compatibility testing, if your application is supported across the platform and browser then you need to consider the cloud-based testing tool.
When it comes to cloud-based testing tools BrowserStack is the first choice of organization. As you know you can have only one version of the Chrome browser, if you want to test multiple versions of the chrome browser BrowserStack can do that with minimal effort. Similarly, the BrowserStack reduces the cost of infrastructure as it is a SaaS platform. React, Cypress and BrowserStack can help you in the uninterrupted delivery of applications without compromising the quality.