Explore the world of testing React Native applications using Typescript and Jest

Trying to kick off a test project using react-native/expo and typescript. Started with the expo's basic typescript template.

For testing, followed the expo's documentation on testing with Jest. Added jest-expo and react-test-renderer as dev dependencies, and updated the package.json according to the docs:

{
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start": "expo start",
    ...
    "test": "jest"
  },
  "dependencies": {
    "expo": "~41.0.1",
    "expo-status-bar": "~1.0.4",
    "react": "16.13.1",
    "react-dom": "16.13.1",
    "react-native": "https://github.com/expo/react-native/archive/sdk-41.0.0.tar.gz",
    "react-native-web": "~0.13.12"
  },
  "devDependencies": {
    "@babel/core": "^7.9.0",
    "@types/jest": "^26.0.23",
    "@types/react": "~16.9.35",
    "@types/react-native": "~0.63.2",
    "@types/react-test-renderer": "^17.0.1",
    "jest-expo": "^41.0.0",
    "react-test-renderer": "^17.0.2",
    "typescript": "~4.0.0"
  },
  "private": true,
  "jest": {
    "preset": "jest-expo",
    "transformIgnorePatterns": [
      "node_modules/(?!(jest-)?react-native|react-clone-referenced-element|@react-native-community|expo(nent)?|@expo(nent)?/.*|react-navigation|@react-navigation/.*|@unimodules/.*|unimodules|sentry-expo|native-base|@sentry/.*)"
    ]
  }
}

This is the test, App.test.tsx:

import renderer from 'react-test-renderer';
import App from "../App";
import React from "react";

describe('<App />', () => {
    it('has 1 child', () => {
        const tree = renderer.create(<App />).toJSON();
        expect(tree.children.length).toBe(1);
    });
});

In Webstorm editor, encountering 2 errors:

  1. tree Object is possibly 'null'.
  2. Property 'children' does not exist on type 'ReactTestRendererJSON | ReactTestRendererJSON[]'.   Property 'children' does not exist on type 'ReactTestRendererJSON[]'
    .

Also, when running the test, getting a different error for <App />

renderer.create(<App />).toJSON()
:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

Seeking assistance on what might be missing here. How do I effectively test a react native app with typescript and jest?

Answer №1

It appears that there is a glitch or problem with Expo's Jest preset, as I discovered an active GitHub issue linked to the error.

To resolve the issue following the advice from GitHub and echoing Kipnoedels' suggestion, I had to include the following in my jest configuration within the package.json:

"moduleFileExtensions": ["ts", "tsx", "js"]

This means my package.json now resembles something like this:

{
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    ...
    "test": "jest"
  },
  "dependencies": {
    ..
  },
  "devDependencies": {
    ...
  },
  "private": true,
  "jest": {
    "preset": "jest-expo",
    "transformIgnorePatterns": [
      "node_modules/(?!(jest-)?react-native|react-clone-referenced-element|@react-native-community|expo(nent)?|@expo(nent)?/.*|react-navigation|@react-navigation/.*|@unimodules/.*|unimodules|sentry-expo|native-base|@sentry/.*)"
    ],
    "moduleFileExtensions": ["ts", "tsx", "js"]
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Stop the observable interval in Angular when the route changes

I initiated an interval in an Angular component, but the requests are still being made even when I navigate to a different route. How do I halt the interval? //function that returns an observable getAllPolls() { return Observable.interval(2000).swit ...

Guide on transforming observable<User> to Observable<boolean> in Angular 4

As a newcomer in Angular and Mean Stack, I need help implementing the canActivate() method to restrict admin routes. In my service file, the checkAdmin method returns an observable of type "User", but the canActivate method's return type is an observa ...

Lack of MaterialUI Table props causing issues in Storybook

Currently, I am utilizing MaterialUI with some modifications to create a personalized library. My tool of choice for documentation is Storybook, using Typescript. An issue I have encountered is that the storybook table props are not consistently auto-gene ...

Array that provides specific data types for indexes

Could be a tricky question or maybe not feasible, but I've been scratching my head over it for quite some time and just can't seem to crack it. Appreciate any help! The T generic creates a union type: const arrayToArray = <T>(values: T[]) ...

Is there a way for me to trace the source of an unclear typescript error message about redeclaring a block-scoped variable named 'length'?

After deleting my node modules and running yarn, I encountered a new error that stated: node_modules/typescript/lib/lib.dom.d.ts:17687:13 - error TS2451: Cannot redeclare block-scoped variable 'length'. 17687 declare var length: number; Despite ...

The Firebase API key is either missing or invalid when using React Native for Android development

As a first-time user, I'm encountering an issue while trying to connect Firebase to my React Native application. The error message "Error: Missing or invalid FirebaseOptions property 'apiKey'" keeps popping up, despite my attempts to search ...

Defining optional parameters in TypeScript

Currently, I am working on implementing strong typing for a flux framework (specifically Vuex). Here is my current code: const actions = { first(context: Context, payload: string) { return doSomething(context, payload); }, second(context: Context) { r ...

What is the best way to dynamically access or create nested objects by iterating through a loop based on a given number?

Can someone assist me in refactoring a couple of if-statements that are almost identical, but differ only in hierarchy within the currentHierarchie object? I am looking to consolidate these into a loop or similar construct. The number of if statements shou ...

"React Native does not recognize the term 'refs' and returns

Just starting out with react-native and currently attempting to extract x,y coordinates of a view within its parent. The code I am using is as follows: componentDidMount: function() { setTimeout(this.measureView); }, measureView: function() { this.ref ...

Leveraging .tsx components within nested .tsx components in React Native

Currently, I am delving into the world of building apps using TypeScript in React Native. Coming from a background as a Swift developer, adjusting to JavaScript and TypeScript has been an interesting journey. An observation that stood out to me is the cha ...

Extract values from an object using Typescript

Here is my JavaScript code: const { a, b, c } = { a : "hello", b : "stackoverflow", c : "it's greate" }; I am interested in converting this to TypeScript. Is there any solution for this? ...

Tips for troubleshooting React issue (TypeError: Cannot read property 'showModel' of null)

Learn how to set the attribute showModel and give it a value of false: Main.js import React from 'react' import 'bootstrap/dist/css/bootstrap.min.css'; import Form from 'react-bootstrap/Form' import Button from 'react-b ...

Tips for adding an item to an array within a Map using functional programming in TypeScript/JavaScript

As I embark on my transition from object-oriented programming to functional programming in TypeScript, I am encountering challenges. I am trying to convert imperative TypeScript code into a more functional style, but I'm struggling with the following ...

Tips for handling a nested function in a redux action unit test

Currently, I am diving into the world of unit testing to test the functionalities of our react application, particularly focusing on actions. In my initial attempts, I encountered a scenario where I have a function that returns an object with a nested fun ...

How can we generate three planes in geometric space that are perpendicular to the x, y, and z

I have been tasked with creating three plane geometries in a scene, one perpendicular to the x-axis, one perpendicular to the y-axis, and one perpendicular to the z-axis. The desired result should somewhat resemble this image: https://i.sstatic.net/L1K6G.p ...

Update the Angular component once new data is saved in a separate Angular component

I've been diving into the world of MEAN stack and Angular, tackling a method within an angular component called itemListDetailsComponent (found in the .ts file) that looks something like this: onStatusUpdateClick() { this.activatedRoute.queryPar ...

Ionic 2: Inconsistency detected in the expression after it was verified

After going through this response, this solution and this advice (as well as numerous others), I still find myself struggling to comprehend how to resolve this issue in my current approach. The task at hand involves creating an event countdown timer that ...

A guide on implementing TypeScript with React Native's platform-specific extensions

The issue at hand: In my react native project, I am using a custom hook that has platform-specific code. I need to import this hook based on the platform in use. When I import it as import useWifi from 'hooks/use-wifi.android';, everything works ...

Using jest to mock the .save() function in sequelize

Looking for help to mock the .save() function from sequelize using jest? I encountered an error in my code within user.services.test.js. Can anyone assist me with this issue? The error message states: "result.save() is not a function." user.services.te ...

Replace the string title in react-native-segmented-control-tab with an image for a more visually appealing design

I have successfully implemented the react-native-segmented-control-tab library in my project. Currently, my code looks like this: <SegmentedControlTab tabsContainerStyle={styles.tabsContainerStyle} tabStyle={styles.tabSt ...