Ways to conduct testing on React Native Typescript app COMPONENTS using jest

I've been struggling to set up testing for my React Native Typescript Components using Jest. Despite searching through various examples and solutions (such as this one, that one, another link, etc.), I still can't seem to get it working. Even following the setup outlined in the sample project here (with additional info from this source) or trying another example project like this one has not yielded any success.

While some setups allow me to run basic tests, importing a Component results in the following error:

  ● Test suite failed to run

Jest encountered an unexpected token

This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

Here's what you can do:
 • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/en/ecmascript-modules for how to enable it.
 • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
 • If you need a custom transformation specify a "transform" option in your config.
 • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html

Details:

/Users/XXX/node_modules/react-native-iphone-x-helper/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { Dimensions, Platform, StatusBar } from 'react-native';
                                                                                         ^^^^^^

SyntaxError: Cannot use import statement outside a module

  at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14)
  at Object.<anonymous> (node_modules/react-native-paper/lib/commonjs/components/BottomNavigation.tsx:13:1)

File contents:

jest.config.js

module.exports = {
preset: 'react-native',
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node']

}

package.json "jest"

  "jest": {
"preset": "react-native",
"transform": {
  "^.+\\.js$": "<rootDir>/node_modules/react-native/jest/preprocessor.js",
  "\\.(ts|tsx)$": "ts-jest"
},
"globals": {
  "ts-jest": {
    "tsConfig": "tsconfig.jest.json"
  }
},
"moduleFileExtensions": [
  "ts",
  "tsx",
  "js"
],
"testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$"

}

tsconfig.json

{"compilerOptions": {
      "target": "es6",
      "module": "commonjs",
      "allowJs": true,
      "jsx": "react-native",
      "noEmit": true, 
      "strict": true, 
      "noUnusedLocals": true,                      
      "noUnusedParameters": true,                 
      "noImplicitReturns": true,          
      "noFallthroughCasesInSwitch": true,       
      "moduleResolution": "node",               
      "allowSyntheticDefaultImports": true,
      "esModuleInterop": true, 
      "skipLibCheck": true,                           
      "forceConsistentCasingInFileNames": true        
    }, "include": [
        "src"
      ]}

If anyone could provide me with a functional example, I would greatly appreciate it.

Answer №1

Discovered a successful setup example: configurations with test execution support.

I omitted the jest.setup.js file and also excluded the line

 setupFilesAfterEnv: ['./jest.setup.js'],

from the jest.config.js file.

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

The parameter 'NextApiRequest' cannot be assigned to the parameter 'Request'

I encountered a typescript issue that states: Argument of type 'NextApiRequest' is not assignable to parameter of type 'Request'. Type 'NextApiRequest' is not assignable to type '{ url: string; }'. Types of pro ...

Error encountered during npm installation: rollbackFailedOptional

section, I encountered an issue while attempting to install new packages using "npm install". An error message was displayed as follows: rollbackFailedOptional: verb npm-session 585aaecfe5f9a82 Below are the versions of Node.js and npm that were util ...

Tips on filtering an array in a JSON response based on certain conditions in Angular 7

Looking to extract a specific array from a JSON response based on mismatched dataIDs and parentDataIDs using TypeScript in Angular 7. { "data":[ { "dataId":"Atlanta", "parentDataId":"America" }, { "dataId":"Newyork", ...

What method can I use to replace the status bar from the top?

Is there a way to smoothly slide in and out a <View/> on React Native iOS, similar to the animation sequences shown in the images below? ...

`Can incompatible Typescript types be allowed for assignment?`

Currently, I am faced with the challenge of sharing type definitions between my server and front-end. These definitions are stored in a separate npm package that both installations utilize. The issue arises on the front-end where variables containing Objec ...

Angular's Integration with PayPal for Shipping Costs

I am facing an issue with my e-commerce website where the receipt only displays the total payment of the items purchased. I have searched for an SDK that supports Angular or TypeScript PayPal integration, but could only find one for JavaScript which did ...

The webpack development server refreshes the page just one time

I've been searching through various issues on Stack Overflow but haven't had any luck. It seems like most solutions are for an older version of webpack-dev-server. Despite trying numerous things, my app just won't reload or rebuild more tha ...

What is the process for retrieving the chosen country code using material-ui-phone-number?

When incorporating user input for phone numbers, I have opted to utilize a package titled material-ui-phone-number. However, the challenge arises when attempting to retrieve the country code to verify if the user has included a 0 after the code. This infor ...

Instructions for implementing personalized horizontal and vertical scrolling within Angular 9

I am currently working on an angular application where users can upload files, and I display the contents of the file on the user interface. These files may be quite long, so I would need vertical scrolling to navigate through them easily. Additionally, fo ...

Unit testing in Angular 2+ involves testing a directive that has been provided with an injected window object

Currently, I am faced with the challenge of creating a test for a directive that requires a window object to be passed into its constructor. This is the code snippet for the directive: import { Directive, ElementRef, Input, OnChanges, OnDestroy, OnInit ...

What is the best way to define a function agreement in Typescript?

I have created a function that can return `undefined` only when its argument is also `undefined`, otherwise it will always return a value derived from the argument provided. Here's an example of how the function works: function triple(value?: number) ...

Combining multiple 'Eithers' and 'Promises' in fp-ts: A guide to piping and chaining operations

Recently, I began working with fp-ts and wanted to create a method with functional-like behavior that would: Parse a bearer token Verify the validity of the user using the parsed token import { Request } from 'express'; import { either } from & ...

Ways to extract information from an Object and save it into an array

In my Angular2 project, I am working on retrieving JSON data to get all the rooms and store them in an array. Below is the code for the RoomlistService that helps me fetch the correct JSON file: @Injectable() export class RoomlistService { constructor( ...

Upgrading from Sequelize V5 to V6: TypeScript bug - Property 'x' is not recognized in type 'y'

Updating from sequelize 5.x.x to 6.x.x has caused some issues for me. In version 5, everything was working fine but after the upgrade, I started facing TypeScript errors with properties generated via associations when trying to use objects from the include ...

Is there a possibility of a @types/jest version 27 coming out soon?

It appears that all Jest related packages I've come across are currently on version 27, except for this one. I wonder if there's a specific reason for this disparity. The Jest documentation mentions the importance of matching versions with associ ...

Having trouble utilizing yarn to import Mapbox into TypeScript

My process involves using the command: yarn add --dev @types/mapbox-gl @types/geojson This successfully adds mapbox and geojson to my project. I can see them when attempting to import mapboxgl. Next, I create something similar to this: import * as L ...

Why does TypeScript require a generic type parameter when arguments have already been provided?

When I attempted to use the argument p to infer type P, TypeScript still prompted me to provide type P. Why is that? const numberStringConverter = <T extends string | number,P extends {x: any}>(p: P): T => { if(typeof p.x === 'string') ...

The parameter 'host: string | undefined; user: string | undefined' does not match the expected type 'string | ConnectionConfig' and cannot be assigned

My attempt to establish a connection to an AWS MySQL database looks like this: const config = { host: process.env.RDS_HOSTNAME, user: process.env.RDS_USERNAME, password: process.env.RDS_PASSWORD, port: 3306, database: process.env.RDS_DB_NAME, } ...

How to associate an object with a component in Angular2/TypeScript using HTTP

I am currently working on displaying a list of item names retrieved from a REST API. By utilizing the map function on the response observable and subscribing to it, I was able to obtain the parsed items object. Now, my challenge is how to bind this object ...

Searching for two variables in an API using TypeScript pipes

I'm stuck and can't seem to figure out how to pass 2 variables using the approach I have, which involves some rxjs. The issue lies with my search functionality for a navigation app where users input 'from' and 'to' locations i ...