App & Browser Testing Made Easy

Give your users a seamless experience by testing on 3000+ real devices and browsers. Don't compromise with emulators and simulators

Home Guide Test React Native Apps with Cypress

Test React Native Apps with Cypress

By Ganesh Hegde, Community Contributor -

Table of Contents

Cypress is a modern tool for test automation, popular because of its ease of installation, inbuilt support for the various reports, and its capability to write Unit, API, and End to End Tests

Cypress supports almost all modern architecture development frameworks such as Angular, React Native, Vu, as well as MVC-type frameworks.

This article will discuss how to test React Native applications with Cypress.

What is a React Native Application?

React Native is an open-source JavaScript-based framework, that supports building apps on multiple platforms such as Android, iOS, and web applications. The concept here is utilizing the same code base for building all different types of applications.

React Native allows you to access native views, APIs, and components. So the development will be faster and more efficient.

Building React Application

The Expo framework helps to build Native React Applications. It supports Andriod, iOS, and Web Applications built from the same code base. Expo has listed many useful examples in Github.

Using Expo you can build a simple React native app:

  1. Install expo from npm: npm install expo
  2. Create native app with command npx create-react-native-app –template <Example>
  3. Follow the guidelines.
    1. Install expo cli to run your app npm i -g expo-cli
    2. Navigate to your app directory and enter the command: npm run web
    3. The application launches in your browser window. Typically it points to http://localhost:19006/
    4. If you have taken a blank React project template, it should look like the image below. One simple page.

Note: Port might change. Check the console log once you run the command.

Here we have created a react app from an expo blank project template. It contains a minimum set of code. App.js is the main source code, and it looks like below:

import { View, Text } from "react-native";

export default function App() {

  return (

    <View

      style={{

        flex: 1,

        justifyContent: "center",

        alignItems: "center",

      }}

    >

      <Text>Universal React with Expo</Text>

    </View>

  );

}

 

This is done to set up React Applications on your device.

How to perform React app testing with Cypress

Bear in mind that all Cypress testing must be executed on real browsers for accurate results. Start running tests on 30+ versions of the latest browsers across Windows and macOS with BrowserStack. Use instant, hassle-free parallelization to get faster results without compromising on accuracy. Detect bugs before users do by testing software in real user conditions with BrowserStack.

Run Cypress Tests on Real Browsers

The Cypress Tutorial offers detailed guidelines on setting up Cypress.

At a minimum, we have to do the following:

  1. Install Cypress: npm install cypress
  2. Open Cypress Project: npx cypress open

At this point, Cypress creates all basic structures of directories. 

Now, consider our example.  

Expo my-react-app runs on the address http://localhost:19006/  so we need to navigate to this address to test our app.

Our previously created expo app has only one set of text that is “Universal React with Expo”. Let’s validate this with a simple Cypress script.

In your integration folder, create firsttest.js file and add the Cypress script to validate:

describe('My First Test', () => {

    it('Verify Text', () => {

        cy.visit('http://localhost:19006/');

        cy.get("div[id='root']").should('have.text', 'Universal React with Expo');

    });

})

Testing React App with Cypress

In the above code, we are navigating to our local website, and verifying whether the text exists or not.

Validating API calls with React Native and Cypress

Most React Native apps call API endpoints internally so we should be able to validate that as well with Cypress.

Consider that we have a React app that has an API call.

React Application Code

import React, { useEffect, useState } from 'react';

import { ActivityIndicator, FlatList, Text, View } from 'react-native';

export default function App() {

  const [isLoading, setLoading] = useState(true);

  const [data, setData] = useState([]);


  useEffect(() => {

    fetch('https://reqres.in/api/users?page=1')

      .then((response) => response.json())

      .then((json) => setData(json.data))

      .catch((error) => console.error(error))

      .finally(() => setLoading(false));

  }, []);


  return (

    <View style={{ flex: 1, padding: 24 }}>

      {isLoading ? <ActivityIndicator/> : (

        <FlatList

          accessibilityLabel="users"

          data={data}

          renderItem={({ item }) => (

            <Text testID="user" >{item.id}, {item.first_name}, {item.email}</Text>

          )}

        />

      )}

    </View>

  );

};

 

The code above calls API ‘https://reqres.in/api/users?page=1 which returns a set of JSON values. We should be able to assert the contents of body and status, etc.

Cypress Script to Validate API calls in React Native App

describe('My First Test', () => {

    it('Verify API', () => {

        cy.intercept('*/users?*').as('users');

        cy.visit('http://localhost:19006/');

        cy.wait('@users').then(({response}) => {

            expect(response.statusCode).to.eq(200)

            expect(response.body.data.length).to.eq(6)

            expect(response.body.data[0].email).to.eq('george.bluth@reqres.in')

          })




   });

  })

 

In the code above, we are using the Cypress Intercept feature, waiting for API to load. Then we are fetching the response from the API, validating it inside our test:

Run Cypress Tests on Real Browsers for Free

This way we can test React Native Apps in Cypress. Furthermore, we can set the viewport and change it to a different device resolution in order to test the mobile web applications as well.

A major advantage of running Cypress tests on BrowserStack is that it will record videos of test execution. Needless to say, this is immensely helpful when it comes to identifying and debugging unexpected errors or bugs.

With the many advantages Cypress provides, it is natural that QAs want to conduct tests using this particular automation framework. While it may seem slightly complicated at first, simply follow the steps outlined in this article, and Cypress testing will become a regular, easily accomplished task. 

Tags
Automation Testing Cypress

Featured Articles

React Native and Appium – Introduction to Test Automation

Browser compatibility for ReactJS web apps

How to perform Unit testing for Angular apps?