• End to End Testing React Apps With Cypress
  • Author: Rajat S
  • The Nuggets translation Project
  • Permanent link to this article: github.com/xitu/gold-m…
  • Translator: stevens1995
  • Proofreader: YZW7489757, Baddyo

Use Cypress for end-to-end testing of the React application

A brief guide on how to use Cypress for end-to-end testing of React applications.

When I was a junior developer I was often afraid to test my apps. Testing is not easy. But with the right tools, writing test code can definitely be easier and more fun.

Cypress is an end-to-end JavaScript testing framework that makes it easy to set up, write, run, and debug tests.

If you’ve tried an end-to-end testing framework like Puppeteer, you’ll notice that these frameworks turn the browser into an air gap system. As our applications get more complex, the tests get harder to pass. This is why most testers prefer to run tests manually.

In this article, I’ll show you how Cypress can help you build tests that run in a real browser. Cypress provides a very easy-to-use API for automated testing.

Instead of looking at a bland terminal full of messy commands, Cypress comes with its own dashboard that shows us exactly what’s going on in our tests. And since Cypress works in a real browser, we can use Cypress alongside the browser’s development tools.

Tip: When using the React component, you may want to keep in mind the importance of component unit tests. With Bit, you can create a reusable directory of components in your project and add component tests that run independently and show visual results. Give it a try.

Component discovery and collaboration · Bit

Let’s get started.


To establish

Instead of creating an entirely new project, I’ll use an existing project and run my Cypress tests on it.

Here, I have a simple ToDo application written in React.

rajatgeekyants/ToDo-List

Clone the application on your system and run yarn Install to install dependencies.

$ git clone https://github.com/rajatgeekyants/ToDo-List.git
$ yarn install
Copy the code

Note: You can also view the app on Bit. This is where you can import any particular component of your application without worrying about the rest.

Todo by Geekrajat · Bit

With this, I can now move into the beta phase of the app. Let’s install Cypress as the dev Dependency for our application.

$ yarn add cypress -D
Copy the code

Now to open Cypress, all we have to do is run this command.

$ node_modules/.bin/cypress open
Copy the code

This will open Cypress CLI (command line interface) (or dashboard) on your system and create a Cypress. json file and Cypress folder in the root directory of your application. The Cypress folder is where we will write the tests.

If you find the command to open Cypress too long or too hard to remember, you can create a new script in package.json:

"cypress": "cypress open"
Copy the code

Therefore, if you run this script using NPM/Yarn, Cypress CLI (command line interface) should open. Create a new test file in the Integration folder under the Cypress folder. Instead of a normal test file we name like app.test.js, in Cypress the test file has a.spec.js extension.

describe ('First Test', () => {
  it ('is working', () => {
    expect (true).to.equal (true);
  });
});
Copy the code

This is a very simple test that simply checks whether true equals true (which it obviously does). If you open Cypress CLI (command line interface), you will see the new test file automatically listed there. Clicking on the test file will run the test and open the dashboard in your browser, where you can see the test results.

This test is independent of the ToDo application. I’m just showing you how to run tests using Cypress. Now let’s start writing tests for our actual application.


Page access in Cypress

The first step in Cypress testing is to allow Cypress to access the application in the browser. Let’s create a new test file and write the following code in it.

describe ('Second Test', () => {
  it ('Visit the app', () => {
    cy.visit ('/');
  });
});
Copy the code

In the code above, I have an object called cy. This is a global object that gives us access to all the commands presented in the Cypress API. I am using the CY visit command. In this command, I will pass in a ‘/’. Go back to the root directory, go to the cypress.json file, and write this in the file:

{
  "baseUrl": "http://localhost:3000"
}
Copy the code

Now, make sure you run the application using the start script. Then open the Cypress CLI (command line interface) and run the new test file. You’ll see the dashboard open in the browser, and in the dashboard our application runs like this:

If you notice the command log on the left, you’ll see that Cypress is calling XHR in order for the application to open in it.


Check the focus

Here, I’m going to run a test to check if the focus is in the input area after loading.

Before we do this, make sure that the SRC/components/TodoList/index, js input (input) in the area have a value for the new task of the className attribute and autoFocus attribute.

<input
  autoFocus
  className="new task"
  ref={a => (this._inputElement = a)}
  placeholder="enter task"
/>
Copy the code

Without these attributes, our tests are bound to fail. Create a new test file that contains the following code:

describe ('Third Test', () => {
  it ('Focus on the input', () => {
    cy.visit ('/');
    cy.focused ().should ('have.class'.'new task');
  });
});
Copy the code

First, I used the Visit app in Cypress’s dashboard. Once the application is open in the dashboard, I check to see if the Focused elements have a New Task class (class).


Test controlled input

In this test, I will check that the controlled input receives text and sets its value correctly.

describe ('Third Test', () => {
  it ('Accepts input', () = > {const text = 'New Todo';
    cy.visit ('/');
    cy.get ('.new').type (text).should ('have.value', text);
  });
});
Copy the code

In this test, I first applied visit in the Cypress dashboard. Now I want Cypress to enter something in the input field. To find the correct Selector for the input field, click the Open Selector Playground button and click the input field.

Once I’ve got the selector for the input field, I’m going to ask Cypress to type some text into it. To make sure Cypress enters the correct text, I use the should command.


Run tests that do not contain any UI

In cases involving a lot of testing, the UI makes our application run very slowly. You don’t see any UI during continuous integration anyway, so why load it?

To run our tests without launching any Cypress UI, we first add a new script to the package.json file.

"cypress:all": "cypress run"
Copy the code

By running this script, Cypress will run all the tests and provide the results directly at the command terminal itself.

Cypress will even record a video of the test for you to watch if you’re worried that you didn’t actually see it play.


Create end-to-end tests in Cypress

Cypress is most useful when we use it for integration testing. But end-to-end testing ensures that nothing is missing throughout the application.

describe ('Sixth Tests', () => {
  context ('No Todos', () => {
    it ('Adds a new todo', () => {
      cy.visit ('/');
      cy.get ('.new').type ('New todo').type ('{enter}');
    });
  });
});
Copy the code

Here, I create an end-to-end test. I first asked Cypress to visit the app. Cypress then gets it using the.new selector of the text box. Cypress will then enter the text New Todo. Finally, I let Cypress simulate enter, thus creating a new Todo.


What’s next?

Cypress can do many other things as well. For example, we can test a feature change, or we can access a step-by-step log of the test. In addition, Cypress can do a lot of other things in the React server rendering application, which I’ll cover in the next article.


Develop learning

  • 5 Tools For Faster Development In React
  • Testing your React App with Puppeteer and Jest
  • How to Test React Components using Jest and Enzyme

If you find any mistakes in your translation or other areas that need to be improved, you are welcome to the Nuggets Translation Program to revise and PR your translation, and you can also get the corresponding reward points. The permanent link to this article at the beginning of this article is the MarkDown link to this article on GitHub.


The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, front-end, back-end, blockchain, products, design, artificial intelligence and other fields. If you want to see more high-quality translation, please continue to pay attention to the Translation plan of Digging Gold, the official Weibo, Zhihu column.