Encountering difficulties with named exports while attempting to execute unit testing with jest

My attempt to write unit test cases has hit a roadblock. Whenever I run the command npm run test for a specific file, I encounter an error Cannot find module '@decorators' for the named exports that I have included in my application. The same issue arises for another named export @entities. Below is the content of my jest config file located in the root folder. Just to provide some context, I am working on a nestjs project.

module.exports = {
  moduleFileExtensions: ['js', 'json', 'ts'],
  rootDir: '.',
  testEnvironment: 'node',
  transform: {
    '^.+\\.(t|j)s$': 'ts-jest',
  },
  moduleNameMapper: {
    '^@entities/(.*)$': 'src/entities/$1',
    '^@decorators/(.*)$': 'src/utils/decorators/$1',
  },
};

I'm seeking assistance in resolving this issue. I've tried various approaches in the jest config but none seem to be effective.

Here's the updated jest config in package.json:

"jest": {
    "moduleNameMapper": {
      "^src/(.*)$": "<rootDir>/$1",
      "^@decorators/(.*)$": "<rootDir>/utils/decorators/$1",
      "^entities/(.*)$": "<rootDir>/entities/$1"
    },
    "moduleFileExtensions": [
      "js",
      "json",
      "ts"
    ],
    "rootDir": "src",
    "testRegex": ".*\\.spec\\.ts$",
    "transform": {
      "^.+\\.(t|j)s$": "ts-jest"
    },
    "collectCoverageFrom": [
      "**/*.(t|j)s"
    ],
    "coverageDirectory": "../coverage",
    "testEnvironment": "node"
  }

Error details:

Test suite failed to run

    Cannot find module '@decorators' from 'modules/test2/entities/test2.entity.ts'

    Require stack:
      modules/test2/entities/test2.entity.ts
      modules/test1/entities/test1.entity.ts
      entities/index.ts
      modules/test-module/test.service.ts
      modules/test-module/test.service.spec.ts

      1 | import { ObjectType } from '@nestjs/graphql';
      2 | import { Entity } from 'typeorm';
    > 3 | import {
        | ^
      4 |   TimestampColumnOptional,
      5 |   StringColumnOptional,
      6 |   IntColumnOptional,
      at Resolver._throwModNotFoundError (../node_modules/jest-resolve/build/resolver.js:428:11)

In my entity file, I have added custom decorators which are imported as shown in the example below. While the project functions correctly, the issue only arises during unit testing.

import {
  IntColumnOptional,
  StringColumnOptional,
  BooleanColumnOptional
} from '@decorators';

Answer №1

"^@decorators/(.*)$ doesn't align with @decorators, causing Jest to be unsure of the file reference for @decorators. It's advisable to include

^@decorators$': 'src/utils/decorators'
in the jest configuration to resolve this issue and ensure smooth functionality.

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

Challenges in designing components in Angular 2.0 and beyond

Issue at hand - There are two input controls on the same page, each belonging to separate components. When a value is entered into the first input box, it calculates the square value and updates the second input control accordingly. Conversely, if the v ...

Assemblage of Enumerations in TypeScript

I am currently working with Vue.js, specifically dealing with Vue components. Within my codebase, I often find myself needing to compare values to an enum. While this works seamlessly in the script section of a .vue file, it poses a challenge in the HTML p ...

The value stored within an object does not automatically refresh when using the useState hook

const increaseOffsetBy24 = () => { setHasMore(false); dispatch(contentList(paramsData)); setParamsData((prevState) => ({ ...prevState, offset: prevState.offset + 24, })); setHasMore(true); }; This function increment ...

Tips for tidying up duplicated typescript content sourced from a pre-existing library

Seeking guidance on implementing best practices and gaining a better understanding of my approach. After discovering the library react-google-calendar-api, I successfully installed it using npm in my React project. However, I wanted to expand its function ...

Implementing Data Binding with Ajax Responses in Angular 2 TypeScript Using the FetchApi Method

I am working on my first angular2 application with typescript. I have successfully fetched results using fetchApi but I am struggling to display them in the views. Can someone please guide me on how to present my data in the views? Thank you. App.componen ...

Having difficulty retrieving JSON data from a NodeJS server built with Typescript

My project involves using NodeJS + Express on the back end to send JSON data as a POST response to the front end through JQuery. I'm facing an issue where the message is not reaching the front end, which utilizes a JQuery AJAX call. It's puzzling ...

Encountering issues when attempting to deploy an Angular 8 application locally on IIS, receiving an error stating 'The server is returning a non-JavaScript MIME type of "text/html"'

Trying to deploy my Angular 8 application hosted within my ASP.NET Core application in the wwwroot folder has been a bit challenging. Previously, I had successfully accomplished this by following these steps: Adjusted the web.config file of the ASP.NET C ...

Compiling an Angular project with an external library in AOT mode using angular-cli is causing issues and not compiling successfully

Embarking on a fresh new project, I utilized angular-cli 8.1.2 for the generation process. The goal is to establish a shared library that caters to multiple microservices (apps). This particular library should remain separate from the applications folder, ...

The presence of React Router in Office JS Excel results in a blank screen

My current project involves developing add-ins for Excel using TypeScript and React. However, I have encountered numerous challenges along the way. Unlike a typical CRA React boilerplate web application, the Office add-in behaves differently. To illustrate ...

Assessing karma: quantifying the reach of unexamined code

I successfully implemented testing using Karma and Webpack for my Typescript sandbox project. The code coverage data is gathered by Istanbul Instrumenter Loader, but I am facing an issue where the reported coverage of 100% is misleading because it only inc ...

Using Typescript to define the type for React's useState() setter function whenever

I'm working on setting up a React Context to handle parameters mode and setMode, which act as getter and setter for a React state. This is necessary in order to update the CSS mode (light / dark) from child components. I'm encountering a Typescr ...

Trying to access the TemplateRef in Angular2 leads to receiving an empty comment node

Struggling to create a custom sorting component in Angular2 because I'm unable to access a template variable. It's crucial for me to be able to reach the ng-template so that I can duplicate/stamp the element to generate drop zones based on the pr ...

Leveraging JSON.stringify alongside getter/setter in TypeScript

In my TypeScript code, I am utilizing getter/setter accessors. To differentiate between variables and methods with the same name, I have adopted the convention of prefixing the variable with a lower dash, as shown in many examples: private _major: number; ...

A helpful guide on invoking a TypeScript function within a Highcharts click event

MyCustomHighChart.ts export class MyCustomHighChart { highchartsConfiguration: any = { chart: { events: { click(event) { if (!($(event.target)[0].textContent)) { console.l ...

Tips for retrieving a date and time selection from a mat-date-picker and mat select?

I am currently utilizing Angular calendar to display various events. Each event is defined by the following parameters: event:{ title: string, start: Date, end: Date }; As material design does not offer a date-time picker, I have opted for usi ...

Custom type checker that validates whether all properties of a generic object are not null or undefined

In an attempt to create a user-defined type guard function for a specific use-case, I am faced with a challenge: There are over 100 TypeScript functions, each requiring an options object. These functions utilize only certain properties from the object wh ...

Is app.component.ts necessary in an Angular 2 project?

Currently diving into Angular 2 and have a burning question on my mind. Do I really need the app.component.ts file in my project? Each of my folders has its own component and template, so I'm debating if the main component is necessary or if I can rem ...

The OR operator in TypeORM allows for more flexibility in querying multiple conditions

Is there any OR operator in TypeORM that I missed in the documentation or source code? I'm attempting to conduct a simple search using a repository. db.getRepository(MyModel).find({ name : "john", lastName: "doe" }) I am awar ...

Executing a single insert statement in a TypeScript Express application using PostgreSQL is taking over 240 milliseconds to complete

Seeking assistance with optimizing a db insert operation test using mocha for a node.js express app that utilizes fp-ts and pg npm package. The tests run successfully, but the insert test is taking over 240 ms to complete. The database table has a maximum ...

Access to the 'currentUrlTree' property is restricted to the 'Router' class as it is marked as private and cannot be accessed externally

Currently, I am in the process of developing a login feature using jwt. However, I am encountering an error when attempting to retrieve the current URL of the active route as shown below. Error Message: [default] /Users/~/src/app/app.component.ts:51:75 P ...