DZone
Web Dev Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Web Dev Zone > Test React Native Apps With Cypress

Test React Native Apps With Cypress

Get started with Cypress.

Ganesh Hegde user avatar by
Ganesh Hegde
CORE ·
Mar. 27, 22 · Web Dev Zone · Tutorial
Like (3)
Save
Tweet
2.75K Views

Join the DZone community and get the full member experience.

Join 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. 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 the 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: 

JavaScript
 
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

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:

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

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

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

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

    });

})


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.

JavaScript
 
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

JavaScript
 
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:


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.

Published at DZone with permission of Ganesh Hegde, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Chopping the Monolith: The Demo
  • Flask vs. Django: Which Python Framework to Choose?
  • No Code Expectations vs Reality
  • Is DataOps the Future of the Modern Data Stack?

Comments

Web Dev Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo