How to Run Cypress Tests for your Create-React-App Application
By Technocrat, Community Contributor - May 16, 2023
Create React App (CRA) is an open-source tool created by the Facebook team that lets you quickly and easily set up a new React project without the need to configure complex build tools such as Webpack or Babel.
When you use CRA, it sets up a development environment that includes all the necessary dependencies, build tools, and configuration files required to build a modern React application. You can see your changes reloaded automatically as you make them with the built-in development server.
CRA is widely used in the React community and has become a popular choice for starting new React projects.
CRA is supported and widely used in the React community, as it allows developers to focus on writing code rather than setting up a development environment. It is also flexible enough to allow customization, with options for adding custom configurations, installing additional dependencies, and integrating with various backend APIs.
- Why use Create-React-App to build your application
- Set up the Create React App
- Install Cypress in the App
- Write the component test for Create-React-App using Cypress
- Run Component test for Create-React-App using Cypress
- Cypress E2E test for Create-React-App using Cypress
- Write the E2E test for Create-React-App using Cypress
- Run your Cypress E2E test for Create-React App
- Best Practices for running Cypress Tests on Create-React
Why use Create-React-App to build your application
There are several reasons why you might choose to use Create React App over other alternatives for building your application:
- Simplicity: Create React App provides a simple and straightforward way to set up a development environment for building React applications. It includes all the necessary tools and configurations out-of-the-box, which can save you time and effort.
- Community Support: Create React App has a large and active community of developers who contribute to its development, provide support, and create plugins and extensions that can be used with the tool. This can make it easier to find help and resources when you need them.
- Opinionated Setup: Create React App provides a pre-configured and opinionated setup for building React applications. This can help you avoid common mistakes and ensure that your application follows best practices.
- Familiarity: Create React App is widely used and has become a standard tool for building React applications. If you’re already familiar with the tool, it may be more efficient for you to use the Create React App than to learn a new tool.
Set up the Create React App
To learn about component testing using the Create React App, will create an App with a component test. Our existing app lets you search for names from a list of pre populated names.
Understand the App
Before we can start installing and using Cypress to perform component testing, you must download and install the required dependencies to start the app.
1. Download the Github repository with the application.
2. Open the downloaded repository in VScode.
3. Click Terminal > New Terminal.
4. Install the required dependencies:
npm install
5. Start the development server:
npm run dev
6. Verify the server is up and running at localhost:5173.
Understand the Component
The following image shows the folder structure of the app:
The autocomplete.jsx file includes the state variables declarations:
- suggestions – array of suggestions used to populate the autocomplete menu.
- suggestionIndex – index of the active suggestion used for keyboard navigation.
- suggestionsActive – used to toggle the visibility of the autocomplete suggestions.
- value – autocomplete suggestion that the user has selected.
It includes the onChange event that will be triggered when a user starts typing and searching for a name. It also includes the onClick event that will be triggered when a user clicks a name from the list that populates. The keyDown event listens for keyboard navigation that a user performs. The Suggestions component holds the logic to return suggestions based on the user entry.
Install Cypress in the App
To write a component test for the component described earlier, we need to install Cypress.
1. Open the downloaded repository in VScode.
2. Click Terminal > New Terminal.
3. Run the following command to install Cypress:
npm install cypress --save-dev
4. Run the following command to open Cypress dashboard:
npx cypress open
Write the component test for Create-React-App using Cypress
The component test that we want to write for our app will test the following:
- Verifies that the UI is up and running.
- Verifies that the filtering drop-down is functional.
- Verifies that scrolling through to a name works correctly.
To add the test to the app:
- In VSCode, open the src/component directory.
- Create a new file, autocomplete.cy.jsx.
- Copy the following code in the file. In the autocomplete.cy.jsx file, the component is mounted using the cy.mount command and Save the file.
import Autocomplete from './autocomplete'; import countries from '../data/countries'; describe('Test the autocomplete functionality', () => { beforeEach(() => { cy.mount(<Autocomplete countries={countries} />); }) it('check everything is working in ui', () => { cy.get('[data-cy="heading"]').contains('Search your country:'); cy.get('input[type="text"]').should('have.value', ''); cy.get('[data-cy="suggestion-list"]').should('not.exist'); }) it('check filter is working', () => { cy.get('input[type="text"]').type('no'); cy.get('[data-cy="suggestion-list"]').should('be.visible').as('suggestList'); cy.get('@suggestList').should('have.length', 1); }) it('check selections are working', () => { cy.get('input[type="text"]').as('inputText'); cy.get('@inputText').type('no').type(Cypress._.repeat('{downArrow}{downArrow}', 1)); cy.get('[data-cy="suggestion-list"] li:nth-child(3)').should('have.class', 'active'); cy.get('@inputText').type(Cypress._.repeat('{upArrow}', 1)); cy.get('[data-cy="suggestion-list"] li:nth-child(2)').should('have.class', 'active'); cy.get('[data-cy="suggestion-list"] li:nth-child(2)').click(); cy.get('input[type="text"]').should('have.length', 1); cy.get('[data-cy="suggestion-list"]').should('not.exist'); }) })
Run Cypress Tests on Real Devices
Run Component test for Create-React-App using Cypress
After you have added the component test to your component, you can run the test using the Cypress dashboard.
1. In VSCode, click Terminal > New Terminal.
2. Run the following code:
npx cypress open
3. Click Component Testing > Chrome, and then click Start Component Testing in Chrome.
4. In the Cypress dashboard, click Specs and double-click the autocomplete.cy.jsx file.
The test is complete and the result appears as follows:
Cypress E2E test for Create-React-App using Cypress
For running the Cypress E2E test, using the bstackdemo web app. The test will sign in using an account, log out the current user, and then verify to be on the Sign in page.
Prerequisite
Before you can create the E2E spec for testing, you must install the cypress-xpath dependency.
- In VSCode, click Terminal > New Terminal.
- Open the root project directory.
- Run the following command to open Cypress:
npm install cypress-xpath
Write the E2E test for Create-React-App using Cypress
We will create an empty spec using the E2E testing option that Cypress provides.
1. In VSCode, click Terminal > New Terminal.
2. Run the following command to open Cypress:
npm cypress open
3. Click E2E Testing > Chrome, and then click Start E2E Testing in Chrome.
4. Click Continue to create an empty spec.
5. Set the name of the test as e2e.cy.js and click Create spec.
6. In VSCode, open the cypress/e2e folder.
7. Open the e2e.cy.js file.
8. Copy the following code:
require('cypress-xpath'), describe('empty spec', () => { it('Bstack demo signin', () => { cy.visit('https://bstackdemo.com/signin') cy.get("#username").click(); cy.xpath("//div[text()='demouser']").click(); cy.get("#password").click(); cy.xpath("//div[text()='testingisfun99']").click(); cy.get("#login-btn").click(); cy.get("#logout").should('have.text','Logout') cy.get("#logout").click(); cy.get("#signin").should('have.text','Sign In') }) })
Run Cypress Tests on Real Devices
Run your Cypress E2E test for Create-React App
1. In VSCode, open the directory, bstackdemo-e2e.
2. Click Terminal > New Terminal.
3. Run the following command to open Cypress:
npm cypress open
4. Click E2E Testing > Chrome, and then click Start E2E Testing in Chrome.
5. In the Cypress dashboard, click Specs and double-click the e2e.cy.js file.
Read More: Cypress End to End Testing: Tutorial
The test is complete and shows the result as follows:
Best Practices for running Cypress Tests on Create-React
Some of the best practices that you can note before creating Cypress test cases are:
- Aim to keep each spec file independent of each other. Reduce interdependencies.
- Use assertions correctly such that Cypress commands progress only when explicit conditions are met.
- Consider each scenario as an independent test case in isolation, sign into applications using programs, and manage your application’s state.
- Use the configuration file (*.cy.js) to set your baseURL.
Conclusion
This article demonstrated how Cypress can help you test your React apps created using Create React App. We also went through a quick tutorial on how to run E2E tests using Cypress. Though Cypress is robust and offers ease in creating tests, it does limit the range of browsers and devices that you can test in real-user conditions.
For stable testing, you must simulate real-world devices, and for that, using a real device cloud, such as BrowserStack for Cypress, is a great option. Access to multiple devices helps you predict and handle issues before your product reaches production.