NestJS TypeORM InjectRepository throwing an error: "Cannot access property 'prototype' of undefined"

Encountering an issue while trying to unit test. Here is the error message that I received:

TypeError: Cannot read property 'prototype' of undefined

export class UserService {

constructor(@InjectRepository(User) private readonly userRepository: Repository < User>) { }

spec.ts:

describe('AuthController', () => {
let authController: AuthController;
let authService: AuthService;
let mockRepository = {

};
beforeEach(async () => {
    const module = await Test.createTestingModule({
        imports: [
            TypeOrmModule.forFeature([User]),
        ],
        controllers: [AuthController],
        providers: [AuthService, {
            provide: getRepositoryToken(User),
            useValue: mockRepository
        }]
    }).compile()
    authService = module.get<AuthService>(AuthService);
    authController = module.get<AuthController>(AuthController)
});

Seeking assistance with finding a solution for this problem.

MORE INFO:

It appears that there might be an issue related to typeorm

beforeEach(async () => {
    const module = await Test.createTestingModule({

    }).compile()
    authService = module.get<AuthService>(AuthService);
    authController = module.get<AuthController>(AuthController)
});

Using the provided code snippet results in the same error. It seems like the only problem arises when typeorm is added to the test Module.

The failure seems to stem from the dependency chain: AuthController->AuthService->UserService->TypeORM

For reference, the UserService works successfully when tested using Postman.

No resolution yet:

module = await Test.createTestingModule({
        controllers: [AuthController],
        components: [
            {
                provide: AuthService,
                useValue: {}
            },
            {
                provide: UserService,
                useValue: {}
            },
            {
                provide: getRepositoryToken(User),
                useValue: {}
            }
        ],
        providers: [
            {
                provide: AuthService,
                useValue: {}
            },
            {
                provide: UserService,
                useValue: {}
            },
            {
                provide: getRepositoryToken(User),
                useValue: {}
            }
        ]
    }).compile()
    this.authController = module.get<AuthController>(AuthController)

Additionally

class AuthServiceMock {
    logIn(userName) {
        return { id:100, isDeleted:false, login:"login", password:"password"};
    }

    signUp() {
        return { expireIn: 3600, token:"token" };
    }
}

describe('AuthController', () => {
let module: TestingModule;
let authController: AuthController;
let authService: AuthService;

beforeEach(async () => {
    module = await Test.createTestingModule({
        controllers: [AuthController],
        components: [

        ],
        providers: [
            {
                provide: AuthService,
                useClass: AuthServiceMock
            },
        ]
    }).compile()
    this.authController = module.get<AuthController>(AuthController)
});

Answer №1

After reviewing the project shared in a comment by Kim Kern (https://github.com/rankery/wof-server), it seems that there is a barrel file being used (src/user/index.ts) to export the UserModule.

export * from './user.module';

It appears that importing the content of this barrel file triggers the execution of code within your built version of src/user/user.module.ts, which includes decorating the UserModule class. This, in turn, leads to Typeorm attempting to build a Repository and causing an error.

To resolve this issue, consider removing the export from src/user/index.ts (or deleting the file altogether) and addressing any broken imports resulting from this change.

Answer №2

After successfully passing the User entity to Repository, I was able to see positive results.

@Injectable()
export class UserService {
    constructor(
        @InjectRepository(User)
        private readonly userRepository: Repository<User>
    ) { }

}

To learn more about this technique, check out the documentation available at https://docs.nestjs.com/techniques/database. The docs are very informative and helpful.

Answer №3

After dedicating countless hours to solving the problem, I finally found a solution

 async findAllUsers() {
    
    return await this.userRepository.createCursor(this.userRepository.find()).toArray();
  }

Answer №4

When using TypeOrmModule.forFeature(...), it is necessary to import TypeOrmModule.forRoot(...) as well. However, in a unit test scenario, working with the actual database may not be ideal and mocking out dependencies is preferred.

It is best practice for controllers not to directly access the database; instead, this responsibility lies with the service. Therefore, when testing a controller that only injects a service, declare a mock for AuthService without importing anything:

const module = await Test.createTestingModule({
    controllers: [AuthController],
    providers: [{
        provide: AuthService,
        useValue: authServiceMock
    }]
}).compile()

Similarly, when testing your AuthService which only injects the repository, declare a mockRepository and exclude everything else.

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

Is there a way to verify a user's authorization status within Next.js 12.1.6 middleware?

I'm implementing a Nextjs middleware to redirect unauthenticated users to the login page. It's currently working locally, but not on the remote server: export async function middleware(req: NextRequest) { const { cookies } = req if (!cook ...

When working with React and Typescript, I encountered an issue with refs causing a typescript error: "The property 'current' does not exist on the type '(instance: HTMLInputElement | null) => void'"

I am working on a component that requires a ref prop: import React, {forwardRef, ReactElement, ReactNode, HTMLProps, useRef} from 'react' import styles from './index.module.css' import classNames from 'classnames' import { Ico ...

"I am looking for a way to receive a response from a loopback in Angular7

Currently, I am utilizing angular7 with loopback. While I can successfully retrieve data, I am unsure how to receive error messages and response statuses. It would be helpful for me to understand what my response code is at the time of the request. Output ...

The ultimate guide to testing API routes in Next.js using Jest

In my api directory, there is a function that searches an array of services and retrieves a single service based on the slug provided. Here is the code for the API function: import {services} from '../../../public/data/service.js' export defaul ...

Store Angular 17 control flow in a variable for easy access and manipulation

Many of us are familiar with the trick of "storing the conditional variable in a variable" using *ngIf="assertType(item) as renamedItem" to assign a type to a variable. This technique has always been quite useful for me, as shown in this example: <ng-t ...

Angular does not adhere to globally defined styles

I have defined the margins for mat-expansion-panel in my styles.css file as follows: mat-expansion-panel { margin: 2vh; } Unfortunately, these margins will not be applied to my components unless they are also specified in the local CSS file. Even try ...

Dramatist - shutting down an angular pop-up dialog

I am currently utilizing the Playwright tool to carry out testing on an angular application. One particular scenario involves a modal that is displayed by default when a page is loaded. Despite my best efforts, I have been unable to successfully close this ...

Error message in Angular 2 RC-4: "Type 'FormGroup' is not compatible with type 'typeof FormGroup'"

I'm currently facing an issue with Angular 2 forms. I have successfully implemented a few forms in my project, but when trying to add this one, I encounter an error from my Angular CLI: Type 'FormGroup' is not assignable to type 'typeo ...

The term 'ObjectId' is typically used as a type, but in this context it is being incorrectly used as a value

I've been scouring for an answer without success. As a newcomer to both stackoverflow and typescript, I've encountered an issue while creating a Mongoose Schema. Here's a snippet of my code: import { Schema, ObjectId } from 'mongoose&a ...

Enzyme/Jest Testing Issue - Invariant Violation: The specified container is not a valid DOM element

I have recently started exploring unit testing and I am encountering the following error: Invariant Violation: Target container is not a DOM element. After reviewing my app.js file, I suspect that the issue lies with the line ReactDOM.render(, document.get ...

Customizing event typings for OpenTok in Typescript

Currently, I am working on integrating chat functionality using the 'signal' events with the OpenTok API. Here is my event listener that successfully receives the signal: // Listen for signal CHAT_MESSAGE sess.on('signal:CHAT_MESSAGE', ...

What methods exist for creating visual representations of data from a table without relying on plotting libraries?

Is there a way to plot graphs directly from a Data Table without the need for external graph libraries like plotly or highcharts? Ideally, I am looking for a solution similar to ag-grid where the functionality comes built-in without requiring manual code ...

How can I pass DOCUMENT in Angular?

In my directive, I use dependency injection to access the DOCUMENT and set up an event listener: constructor(@Inject(DOCUMENT) private document: Document) {} ngOnInit() { this.document.addEventListener('click', this.clicked, true); } @Bound ...

I received an undefined value from the Jest snapshot

Today, I embarked on my first journey into writing Jest testing files and found myself facing doubts and errors. I decided to create a headers.test.js file as my testing file and after running the command, I was pleased to see the output in the terminal s ...

"I'm looking for a way to store and fetch TypeScript objects with PouchDB. Any suggestions on

As someone who is new to typescript and web development, I am eager to incorporate PouchDB into my typescript project to store my objects. Despite the lack of documentation, I am struggling to find the correct approach. I have created typescript objects t ...

Angular 7 navigation successfully updates the URL, but fails to load the corresponding component

Despite exhausting all other options, I am still facing a persistent issue: when trying to navigate to a different component, the URL changes but the destination component fails to load. Explanation: Upon entering the App, the user is directed to either ...

Looking to integrate Nestjs with additional Redis functionalities?

I recently set up a nestjs backend with redis for caching by following the instructions in the official documentation https://docs.nestjs.com/techniques/caching#in-memory-cache. To achieve this, I utilized the cache-manager-redis-store package and include ...

The specific property 'splice' cannot be found within type 'T'

As I delve into working with TypeScript, an unexpected error arises: Property 'splice' does not exist on type 'T'. type Item = { name: string, body: string, imgOne: string, imgTwo: string, }[] // Another file contains this func ...

Unable to access property 'create' which is undefined

On my Ionic3 page, I am trying to trigger a modal open from within a click event function. export class HomePage { .... .... .... loadPos() { var randomLocations = Microsoft.Maps.TestDataGenerator.getLocations(5, this.map.getBounds()); ...

The attribute 'forEach' is not recognized on the data type 'string | string[]'

I'm experiencing an issue with the following code snippet: @Where( ['owner', 'Manager', 'Email', 'productEmail', 'Region'], (keys: string[], values: unknown) => { const query = {}; ...