Troubleshooting TypeScript error in snapshot testing with react-native-vector-icons/MaterialIcons and Jest-Expo

Currently, I am in the process of familiarizing myself with Jest and am working on creating my initial snapshot tests for components using react-native & expo. Interestingly, when running the test without the Icon component from 'react-native-vector-icons/MaterialIcons' inside my component, everything works smoothly. However, as soon as I decide to include the Icon component in the test, an error arises:

ReferenceError: You are trying to `import` a file after the Jest environment has been torn down.

  at Object.get Text [as Text] (node_modules/react-native/Libraries/react-native/react-native-implementation.js:118:12)
  at Icon.render (node_modules/@expo/vector-icons/build/vendor/react-native-vector-icons/lib/create-icon-set.js:120:58)
  at finishClassComponent (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:7618:31)
  at updateClassComponent (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:7568:24)
  at beginWork (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:9043:16)

  Cannot log after tests are done. Did you forget to wait for something async in your test?
    Attempted to log "Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/functio
n (for composite components) but got: object. You likely forgot to export your component from the file it's defined in, or you might 
have mixed up default and named imports.

Check the render method of `Icon`.
    in Icon (created by Icon)
    in Icon".

To provide context, here is the code I have written for the test:

import React from 'react'
import * as Icon from 'react-native-vector-icons/MaterialIcons'
import renderer from 'react-test-renderer'

it('Renders an icon', () => {
  const tree = renderer.create(
    <Icon.default
    size={20}
    color={ 'grey' }
    name={ true ? 'check-box' : 'check-box-outline-blank' }
  />
  ).toJSON()
  expect(tree).toMatchSnapshot();
})

Furthermore, this is how my jest configuration appears in package.json:

"jest": {
    "preset": "jest-expo",
    "transformIgnorePatterns": [
      "node_modules/(?!((jest-)?react-native|react-clone-referenced-element|expo(nent)?|@expo(nent)?/.*|react-navigation|react-native-vector-icons|@unimodules))"
    ],
    "testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "jsx",
      "json",
      "android.ts",
      "android.tsx"
    ]
  },

While these components operate perfectly outside of tests, incorporating them into my Jest tests seems to trigger issues.

Answer №1

Upon closer examination of the jest documentation, I discovered a solution by implementing mocks.

By incorporating the following code snippet into the test, it appears to resolve the issue:

jest.mock('react-native-vector-icons/MaterialIcons', () => 'Icon')

Answer №2

Take a look at this more detailed example:


jest.mock('react-native-vector-icons/MaterialIcons', () => ({
  loadFont: jest.fn(),
  Icon: 'Icon',
}));
jest.mock('react-native-vector-icons/FontAwesome', () => ({
  loadFont: jest.fn(),
  Icon: 'Icon',
}));
jest.mock('react-native-vector-icons/MaterialCommunityIcons', () => ({
  loadFont: jest.fn(),
  Icon: 'Icon',
}));

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

Angular throws a 404 error when making a JSONP http request

I've been incorporating Mailchimp integration into an Angular application. For using it in pure JS, I retrieved the code from the embedded form on the Mailchimp site: <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js ...

Struggling to deploy my frontend application using tRPC on Netlify

While using React Typescript, I have followed the tRPC docs for setting up the server/client, but when deploying, I encountered this error. It works fine locally, so why is this happening during deployment? 8:41:46 AM: TS2339: Property 'createClient&a ...

Verify that the user's input falls within a specified range before adding it to the result

Currently, I'm trying to implement validation on user input. The idea is that if a user enters a number between 1 and 10, I want to add a 0 in front of it. For example, if the user inputs 4, I would like to store the value 04. While I am comfortable d ...

The immutability of TypeScript's `as const` compared to JavaScript's Map object

Let's delve into a straightforward example: const simpleObject = { one: 'one', two: 'two', three: 'three' } Historically, pre ES2015 objects did not guarantee the preservation of key order upon retrieval. However, ...

Tips for configuring identical libraries under different names

As a Japanese web developer, I struggle with my English skills, so please bear with me. Currently, I am utilizing an npm library. I have forked the library and made some modifications to it. In order to incorporate these changes, I updated my package.js ...

Shifting an item between various components to modify its properties

I am currently working with an HTML table that looks like this: <table> <tr> <td>Name</td> <td>Surname</td> <td>ID Number</td> <td>Edit</td> </tr> <tr *ngFor="let p ...

There seems to be an issue with the authorization function in nextauthjs utilizing TypeScript

In my NextJS application utilizing nextAuth with TypeScript, I am encountering difficulties implementing the credentials provider. Below is a snippet from my api\auth\[...nextauth]\route.ts file: CredentialsProvider({ name: 'cre ...

Tips for fixing TypeScript TS7031 issue related to v-slot in VueJS!

I am currently working on a project using Vue.js 3 with Typescript and vee-validate. I encountered an error while building the project. Error message: TS7031 - Semantic error. Binding element 'field' implicitly has an 'any' type. The ...

Creating a customized control in Nativescript: Enhancing Dependency Properties

I am currently developing a custom component that consists of a list of buttons. Whenever a user clicks on a button, I modify its CSS class and then I want to add it to a custom property called "selectedItems" in order to retrieve it in my ViewModel. How ...

Two-way conditional type mapping

Currently, I am working on mapping the various "data types" of an object to a corresponding "schema" type. If the property's data type is boolean, it should be mapped to the "BooleanComponents" type The code snippet below demonstrates how this can ...

Pressing Enter in a Material-UI Dialog does not trigger form submission

I am currently facing an issue with my modal dialog component. I have two buttons within the dialog, with one functioning as a submit button. My goal is to make the 'Enter' key trigger the submit action as well. Below is the code snippet for thi ...

What is the most effective way to loop and render elements within JSX?

Trying to achieve this functionality: import React from 'react'; export default class HelloWorld extends React.Component { public render(): JSX.Element { let elements = {"0": "aaaaa"}; return ( ...

The React component incorporating a Three.js canvas functions intermittently

Recently, I created a React component that appends a three.js canvas to an HTMLDivElement using a ref object. Here's the code snippet: import { useEffect, useRef } from "react"; import * as THREE from 'three'; export default funct ...

Retrieving automatically generated module

In my setup, there is a component that takes in some data and dynamically generates other components using ngx-charts. This specific part acts as the directive @Directive({ selector: '[ad-host]', }) export class PresentationDirective { c ...

Discovering an entry that lacks a specific value within an array in the records

Currently, I am utilizing sequelize along with typescript in a node environment (with a postgresql database). Here is the model that I have defined: id: number, someField: string, arr1: number[], arr2: number[] My objective is to retrieve all records wher ...

Issue - Attempting to add an expectation result prior to the start of a test specification

Seeking assistance to comprehend why I am facing this problem while executing protractor e2e test in a jenkins job, but everything works fine when I run it locally. https://i.sstatic.net/TusZl.png Appreciate any help in advance. ...

Navigating nested routes in React Router: a comprehensive guide

I need help with integrating nested routes into my app. Can someone guide me on how to add nested routes? Here is the structure of my app: import { Route, Routes } from 'react-router-dom'; import routes, { RouteModel } from './router/routes ...

Angular 12 error: Unable to locate route with passed parameters

Explaining how I define the route in my app-routing : { path: 'user/:id', component: UserDetailComponent }, Defining the Navigation for Users <a [routerLink]="['/user', user.id]">detail</a> Inside the UserDeta ...

An issue with the updating process in React Native's useState function

I am currently facing a challenge with an infinite scroll listview in react native. I have created a calendar list that needs to dynamically change based on the selected company provided as a prop. The issue arises when the prop (and the myCompany state) a ...

The method for dynamically eliminating an item from a useState array upon activation of a function

I'm currently working on a React project where I have an array of items and when one is selected, it's added to a useState hook with the following code: setSelectedHomeTypes([...selectedHomeTypes, selected]) console.log(selectedHomeTypes) Now, I ...