Encountering an issue while running Jest tests in NodeJS due to TypeScript configuration file error

I've been encountering some issues while running Jest tests. It seems to be related to a TypeScript config file, and my search for solutions hasn't been very fruitful. The setup I'm using involves NodeJS, TypeORM, and TypeScript.

When I attempt to run yarn test, the following error arises:

Error: Jest: Failed to parse the TypeScript config file

C:\Users\demis\Documents\Projects\Personal\nlw_node\jest.config.ts TypeError: registerer.enabled is not a function*** at readConfigFileAndSetRootDir (C:\Users\demis\Documents\Projects\Personal\nlw_node\node_modules\jest-config\build\readConfigFileAndSetRootDir.js:150:13) at readConfig (C:\Users\demis\Documents\Projects\Personal\nlw_node\node_modules\jest-config\build\index.js:217:18) at readConfigs (C:\Users\demis\Documents\Projects\Personal\nlw_node\node_modules\jest-config\build\index.js:406:26) at runCLI (C:\Users\demis\Documents\Projects\Personal\nlw_node\node_modules@jest\core\build\cli\index.js:230:59) at Object.run (C:\Users\demis\Documents\Projects\Personal\nlw_node\node_modules\jest-cli\build\cli\index.js:163:37)

First.test.ts:

describe("First", () => {
  it("should", () => {
    expect(2 + 2).toBe(4);
  });
});

jest.config.ts:

export default {
  bail: true,
  clearMocks: true,
  coverageProvider: "v8",
  preset: "ts-jest",
  testEnvironment: "node",
  testMatch: ["**/tests/*.test.ts"]
};

tsconfig.json:

{
   "compilerOptions": {
      "lib": [
         "es5",
         "es6"
      ],
      "target": "es5",
      "module": "commonjs",
      "moduleResolution": "node",
      "outDir": "./build",
      "emitDecoratorMetadata": true,
      "experimentalDecorators": true,
      "sourceMap": true
   }
}

package.json:

{
  "name": "nlw_node",
  "version": "0.0.1",
  "description": "A fantastic project built with TypeORM.",
  "devDependencies": {
    "@types/express": "^4.17.11",
    "@types/jest": "^26.0.20",
    "@types/node": "^8.0.29",
    "@types/uuid": "^8.3.0",
    "jest": "^26.6.3",
    "nodemon": "^2.0.7",
    "ts-jest": "^26.5.3",
    "ts-node": "3.3.0",
    "typescript": "^4.2.3"
  },
  "dependencies": {
    "body-parser": "^1.18.1",
    "express": "^4.15.4",
    "mysql": "^2.14.1",
    "reflect-metadata": "^0.1.10",
    "typeorm": "0.2.31",
    "uuid": "^8.3.2"
  },
  "scripts": {
    "start": "nodemon src/index.ts",
    "typeorm": "ts-node node_modules/typeorm/cli.js",
    "test": "jest"
  }
}

ormconfig.ts:

{
  "type": "mysql",
  "host": "localhost",
  "port": 3306,
  "username": "root",
  "password": "root",
  "database": "nlw_node",
  "synchronize": true,
  "logging": false,
  "entities": ["src/api/models/**.ts"],
  "migrations": ["src/database/migrations/**.ts"],
 
  "cli": {
    "entitiesDir": "src/entity",
    "migrationsDir": "./src/database/migrations",
    "subscribersDir": "src/subscriber"
  }
}

Answer №1

To upgrade, uninstall the ts-node package and replace it with ts-node-dev.

Answer №2

I encountered a seemingly trivial problem. The culprit was a sneaky comma lingering at the end of my tsconfig file, as shown below:

{
  ...
  "ts-node": {
    "compilerOptions": {
      "jsx": "react-jsx",
      "module": "commonjs",
      "jsxImportSource": "",
      "paths": {
        "~/*": [
          "./src/*"
        ]
      }
    },
    "require": [
      "tsconfig-paths/register"
    ],
    "transpileOnly": true
  }, // <----- This was the offending comma
}

Simply removing that troublesome comma resolved the issue I was facing.

Answer №3

Earlier today, I encountered the same issue while attempting to execute tests using jest with Angular and Typescript.

The issue was resolved after I re-installed jest:

npm install --save-dev jest

Subsequently, this revealed a configuration problem within my setup, but thankfully the failed error is no longer present.

Answer №4

If you already have ts-node installed, one solution to this problem could be to install ts-jest.

Answer №5

Make sure to verify that the babel.config.js file is located in the project's root / directory. If it is not there, please refer to the instructions provided here

Answer №6

After making adjustments to my tsconfig.json file by adding the exclude and include properties, I was able to get it to work perfectly.

{
  "compilerOptions": {
    "target": "esnext",
    "module": "commonjs",
    "rootDir": "./",
    "baseUrl": "./src",
    "outDir": "./dist",
    "allowJs": true,
    "noEmit": false,
    "noEmitOnError": true,
    "noUnusedLocals": true,
    "strict": true,
    "moduleResolution": "node",
    "sourceMap": true,
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "forceConsistentCasingInFileNames": true,
    "removeComments": true,
    "skipLibCheck": true,
    "typeRoots": [
      "@types",
      "./node_modules/@types"
    ]
  },
  "exclude": [
    "node_modules",
    "dist"
  ],
  "include": [
    "src/**/*",
    "src/__tests__",
    "jest.config.js"
  ]
}

Answer №7

Encountered a similar issue where the tests were only running once.

Resolving it required deleting the node_modules and yarn.lock directories, followed by a complete reinstallation of all dependencies.

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

Using Jest: A guide to utilizing a mocked class instance

When working on my frontend React application, I decided to use the auth0-js library for authentication purposes. This library provides the WebAuth class which I utilize in my code by creating an instance like so: import { WebAuth } from 'auth0-js&ap ...

Using TypeScript arrow function parentheses in the filter function

If I have an array of movie objects like this: const movies: Movie[] = [ movie1, movie2, movie3, movie4 ]; And if I want to remove a specific movie from the array, such as movie2, I can use the following code: movies = movies.filter( m => m !== ...

Angular displays error ERR_UNKNOWN_URL_SCHEME when attempting to retrieve an image saved in a blob

As I transition my app from Electron to Angular, one of my main objectives is to display an image uploaded by a user. Here's how I attempted to achieve this: page.component.ts uploadImageFile(){ fileDialog({}, files =>{ //Utilizing the fileDi ...

What steps can be taken to resolve the issue of being unable to rename an element in Typescript?

Why does VS code editor sometimes prevent me from renaming my typescript symbol using the f2 key? I keep encountering the error message "This element cannot be renamed." https://i.stack.imgur.com/mmqu9.png In some of my other projects, I am able to renam ...

Overlooking errors in RxJs observables when using Node JS SSE and sharing a subscription

There is a service endpoint for SSE that shares a subscription if the consumer with the same key is already subscribed. If there is an active subscription, the data is polled from another client. The issue arises when the outer subscription fails to catch ...

Refresh a Google chart without having to reload the entire page

I currently have a button that allows me to refresh the data on my page in case there is new data available through an API. Although this button successfully refreshes my datatable, it does not redraw the Google charts I have integrated into my project usi ...

Guide on leveraging the `ConstructorParameter` tool with generic-friendly types

Attempting to extract the constructor parameter type from a class, but the class in question accepts a generic type value. Does anyone know how to achieve this? Encountered error: ConstructorParameters<typeof(DictionaryClass<contentType>)[0]; ...

Guide on transforming an array containing indexed objects into a simple object

Can anyone help me with converting an array of this specific type? place: [ { "_id": "xxxxx", "loc": [ 0: "xxx", 1: "xxx" ] } ] Into something ...

The TypeError encountered in an Ionic pipe states that the property 'toString' cannot be read as it is undefined

I have a news application built in Ionic 4. The pubDate property of the UutinenPage class is being asynchronously assigned a value of data.items[this.id].pubDate in the uutinen.page.ts file. The expected format of this value is something like 2019-02-19 04 ...

React is not displaying the most recent value

During the initial rendering, I start with an empty array for the object date. After trying to retrieve data from an influxDB, React does not re-render to reflect the obtained results. The get function is being called within the useEffect hook (as shown in ...

Guide to defining the typescript type of a component along with its properties

I am facing an issue with my SampleComponent.tsx file: import React from 'react'; type Props = { text: string }; export const SampleComponent: React.FC<Props> = ({text})=><div>{text}</div>; SampleComponent.variant1 = ({tex ...

Displaying the default value in a Material-UI v5 select component

I am looking to display the default value in case nothing has been selected yet for the mui v5 select component below, but currently it appears empty... <StyledCustomDataSelect variant='outlined' labelId='demo-simple- ...

Error in Typescript: Cannot assign type 'string[]' to type 'string'

I'm currently developing a project using Next.js with Typescript and .tsx files, and I'm utilizing Supabase as my database. While everything is functioning perfectly on localhost, I'm encountering an issue when trying to build the project o ...

Is there a way for me to define the type of a prop based on the type of another prop?

I'm not entirely certain how to phrase this inquiry, or which terminology to employ, so I'll do my best in presenting it. My intention is to develop a component that functions on an array of elements and triggers a render function for each eleme ...

Every instance of 'WeakMap' must include the same type parameters

While developing an Ionic App, I encountered a strange issue. Everything was running smoothly until I cloned the source code to a different machine, which resulted in an error that is displayed in the attached image. Even though there are no compilation e ...

How to effectively send an HTTP GET request to a REST API in Angular 2 and save the response in a JSON object

Currently, I am attempting to execute a GET request to the GitHub API using Angular2. The returned data is in JSON format, and my goal is to store it in a JSON object for further processing. While referring to the Angular2 documentation for guidance, I en ...

What is the method for assigning a value to an attribute in HTML?

Is there a way to assign a function's value to an HTML attribute? For example, setting the attribute value to the value returned by the function foo. foo () : string { return "bar"; } I attempted the following without any success. <input type="b ...

How can I bind the ID property of a child component from a parent component in Angular 2 using @Input?

I have a unique requirement in my parent component where I need to generate a child component with a distinct ID, and then pass this ID into the child component. The purpose of passing the unique ID is for the child component to use it within its template. ...

The storage does not reflect updates when using redux-persist with next-redux-wrapper in a Typescript project

I'm currently working on integrating redux-persist with next.js using next-redux-wrapper. However, I'm facing an issue where the storage is not updating and the state is lost during page refresh. Below is my store.ts file: import { createStore, ...

Having trouble deleting JavaScript object properties within a loop?

Struggling to comprehend the behavior of this particular piece of javascript code. const devices = searchResult.results.forEach(device => { const temp = Object.keys(device.fields); for(var property in temp) { if(device.fields.hasOwnPro ...