The issue arises in ts-jest nestjs where there is an attempt to access properties of an undefined

Creating an application using NestJS and utilizing ts-jest for e2e testing. For the code repository, visit: https://github.com/redplane/jest-issue

A controller is set up with the following structure:

@Controller({
  path: 'api/shape',
  scope: Scope.REQUEST,
})
export class ShapeController {
  public constructor(
    @Inject(AppInjectors.SERVICE__JOI)
    private readonly __joiService: IJoiService
  ) {}

  @Get()
  public async processAsync(@Query() query: ProcessShapeQuery): Promise<void> {
    // Validate parameters
    console.log(ShapeDimensions);
    await this.__joiService.validateAsync(query, processImageQueryJoiSchema);
  }
}

Postman API requests work seamlessly, displaying:

{ WIDTH: 'WIDTH', HEIGHT: 'HEIGHT' }

However, during e2e tests using the command:

npm run e2e:api

An error surfaced:

TypeError: Cannot read properties of undefined (reading 'PIXEL')
       5 | export const imageFrameOptionsJoiSchema =  Joi.object<ShapeFrameOptions>({
       6 |   size: Joi.number().min(1),
    >  7 |   unit: Joi.any().valid(ShapeUnits.PIXEL),
         |                                    ^
       8 |   dimension: Joi.any().valid(ShapeDimensions.HEIGHT, ShapeDimensions.WIDTH)
       9 | });
      ...more errors displayed...

Commenting out:

await this.__joiService.validateAsync(query, processImageQueryJoiSchema);

Causes console.log(ShapeDimensions); to return undefined. Enum printouts still function normally.

Referencing my jest.config.ts:

/* eslint-disable */
export default {
  displayName: 'api-e2e',
  preset: '../../jest.preset.js',
  globalSetup: '<rootDir>/src/support/global-setup.ts',
  globalTeardown: '<rootDir>/src/support/global-teardown.ts',
  setupFiles: ['<rootDir>/src/support/test-setup.ts'],
  testEnvironment: 'node',
  transform: {
    '^.+\\.[tj]s$': [
      'ts-jest',
      {
        tsconfig: '<rootDir>/tsconfig.spec.json',
      },
    ],
  },
  moduleNameMapper: {
    "@image-service/api": "<rootDir>/../api/src/index.ts",
    "@image-service/api-business": "<rootDir>/../../libs/api-business/src"
  },
  moduleFileExtensions: ['ts', 'js', 'html'],
  coverageDirectory: '../../coverage/api-e2e',
};

Tried solutions from:

-> No circular dependency detected upon checking

Any suggestions are appreciated.

Thank you,

Answer №1

After taking some time to clear my mind, I suddenly had a breakthrough:

In my jest.config.ts file, I noticed this particular section:

moduleNameMapper: {
    "@image-service/api": "<rootDir>/../api/src/index.ts",
    "@image-service/api-business": "<rootDir>/../../libs/api-business/src"
  },

Previously, when I was working with an older version of NestJS and jest, I needed this configuration to ensure that my test files could recognize my project libraries.

However, with the latest version of NestJS and jest (primarily related to jest), removing this configuration allowed my tests to run successfully.

Therefore, the updated jest.config.ts looks like this:

/* eslint-disable */
export default {
  displayName: 'api-e2e',
  preset: '../../jest.preset.js',
  globalSetup: '<rootDir>/src/support/global-setup.ts',
  globalTeardown: '<rootDir>/src/support/global-teardown.ts',
  setupFiles: ['<rootDir>/src/support/test-setup.ts'],
  testEnvironment: 'node',
  transform: {
    '^.+\\.[tj]s$': [
      'ts-jest',
      {
        tsconfig: '<rootDir>/tsconfig.spec.json',
      },
    ],
  },
  moduleFileExtensions: ['ts', 'js', 'html'],
  coverageDirectory: '../../coverage/api-e2e',
};

The outcome is reflected in this screenshot: https://i.sstatic.net/82vmsqeT.png

I hope this solution proves helpful for anyone facing a similar challenging situation.

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

What is the process for importing a TypeScript module in the StackBlitz editor?

When I enter the editor at Stackblitz.com and start a new Angular project, it comes with default files and folders already set up. In the "Dependencies" section, I decide to add shortid. So, I input that in the designated box and it begins loading the cor ...

What is the process for generating an array of objects using two separate arrays?

Is there a way to efficiently merge two arrays of varying lengths, with the number of items in each array being dynamically determined? I want to combine these arrays to create finalArray as the output. How can this be achieved? My goal is to append each ...

How to use Typescript to find the length of an array consisting of either strings or

I am trying to determine the length of a string or array, stored in a variable with the data type var stepData : string | string[]. Sometimes I receive a single string value, and other times I may receive an array of strings. I need the length of the array ...

Unable to utilize checkboxes for filtering in Angular 2 and beyond

I am working on a project that involves showcasing a list of participants. My goal is to set up a feature that allows filtering these participants based on different providers using checkboxes in real-time. Below is a sample of the participants: [ { ...

Having trouble accessing property '0' of undefined in angular

Below is the code I am currently working on. My goal is to enable editing of the table upon click, but I encountered the error mentioned below. Could someone kindly explain why this is happening and suggest a workaround? <tbody> <tr *ngFor="l ...

Structure of document

Could anyone clarify for me the meaning of (callback[, thisObject]); that is mentioned in the TypeScript documentation here? I am particularly curious about the brackets themselves [, ]. ...

The ngModel directive seems to be failing to bind the select element in Angular 4

One of the challenges I am facing in my application involves a form that includes various data fields such as title, price, category (select), and imageUrl. I have successfully implemented ngModel for all fields except the select element. Strangely, when I ...

Running Jest tests with TypeScript involves executing the tests twice: once for TypeScript files and once for JavaScript files

I’ve recently started writing tests using TypeScript and Jest, but I’m running into an issue where the tests are being executed twice – once for the TS files and then again for the compiled JS files. While the TypeScript tests are passing without an ...

Transferring files from one azure blob container to another

I am currently utilizing the @azure/storage-blob package to manage files within Azure. Within the same Azure storage account, I have two storage containers - one for source files and the other for destination files. My objective is to copy a file from th ...

Trigger an error in TypeScript with an embedded inner error

Is it possible to throw an Error with an inner Error in TypeScript, similar to how it's done in C#? In C#, you can achieve this by catching the exception and throwing a new one with the original exception as its inner exception: try { var a = 3; ...

Most effective method for dividing a massive array in a Node.js setting

As I work on retrieving web request logs from the Cloudflare API for a highly trafficked website within a short time frame of less than 7 days, I encounter some challenges. The Cloudflare API requires start and end parameters for date ranges, restricting ...

Can you explain the purpose of the "=" symbol in the function definition of "export const useAppDispatch: () => AppDispatch = useDispatch" in TypeScript?

Recently, while working on a React app that utilizes react-redux and react-toolkit, I encountered some TypeScript syntax that left me puzzled. export type RootState = ReturnType<typeof store.getState> export type AppDispatch = typeof store.dispatch e ...

How can we pass the onClick prop from a child component to a parent component in React with Typescript?

Currently, I am utilizing React along with TypeScript. I am curious about the process of passing an event from the parent component to a child component using props. Here is an example for better understanding: parent.tsx const ParentComponent: React.F ...

Using jest to simulate a private variable in your code

I am working on unit testing a function that looks like this: export class newClass { private service: ServiceToMock; constructor () { this.service = new ServiceToMock() } callToTest () { this.service.externalCall().then(()=& ...

React TypeScript: Handling OnChange Events for Different Input Types

I am confronted with multiple input fields: <label> <span className="codes__input-label">Count</span> <input type="number" value={this.state.count} onChange={this.onInputChange} /> </label> ...

Leverage the power of React, Material-UI, and Typescript to inherit button props and incorporate a variety of unique

Looking to enhance the Material-UI button with additional variants like "square." How can I create a prop interface to merge/inherit props? Check out the following code snippet: import React from "react"; import { Button as MuiButton } from "@material-u ...

Executing vitest on compiled javascript files

Currently facing issues running vitest on compiled JavaScript. Numerous errors are appearing, such as: TypeError: Cannot read properties of undefined (reading 'spyOn') TypeError: Cannot read properties of undefined (reading 'mock') and ...

Locate and return the index in Typescript

Can you get the index of an element in an array using the array.find() method in TypeScript? For example, I know I can use find to retrieve an object based on a property value, but is it possible to also retrieve the index of that object in the array? ...

"Type 'Unknown' cannot be assigned to the specified type: Typescript Error encountered while using

I encountered an error message in my Redux Observable setup. Any advice on how to resolve this issue? The error states: 'Argument of type 'OperatorFunction<ITodo[], Action<{ params: { url: string; }; } & { result: { todos: ITodo[]; }; ...

Tips for uploading images, like photos, to an iOS application using Appium

I am a beginner in the world of appium automation. Currently, I am attempting to automate an iOS native app using the following stack: appium-webdriverio-javascript-jasmine. Here is some information about my environment: Appium Desktop APP version (or ...