NestJS TypeORM InjectRepository Cannot read property 'prototype' of undefined

nestjs custom repository
nestjs repository pattern
nestjs/typeorm testing
nestjs transactions
nestjs/typeorm querybuilder
typeorm migrations
nestjs model
typeorm update entity

Trying to unit test. Got following error:

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)
});

Can someone share a solution please?

MORE INFO:

So seems like its something wrong with typeorm

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

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

With this code I'm getting exact the same error. So only problem is adding typeorm to this test Module.

So it fails because of dependency: AuthController->AuthService->UserService->TypeORM

Btw just checked UserService using API with Postman and it works fine.

Still no result:

 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)

Also

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)
});

I looked at the project you provided in a comment under Kim Kern (https://github.com/rankery/wof-server)

You are using a barrel file (src/user/index.ts), exporting the UserModule

export * from './user.module';

I guess you are using this barrel file to import the module later on.

Now, every time the content of the barrel file is imported , the code contained in the built version of your src/user/user.module.ts is executed, which include the decoration of the UserModule class, which in turns will make Typeorm try to build a Repository, which causes the error.

You should remove this export from src/user/index.ts (or simply delete the file) and fix the broken imports caused by this removal and it should work.

TypeError: Cannot read property 'findOne' of undefined � Issue #405 , nestjs / typeorm TypeError: Cannot read property 'findOne' of undefined #405 constructor( @InjectRepository(UserRepository) private readonly userRepository: UserRepository, with this using Connection from typeorm Running npm run console:dev -- getAUser fails with the error: TypeError: Cannot read property 'findOne' of undefined Here is cli.service.ts. import { Injectable } from '@nestjs/common'; import { ConsoleService } from 'nestjs-console'; im

I just passed the User entity to Repository and it works.

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

}

Checkout docs from here: https://docs.nestjs.com/techniques/database. They have pretty good docs.

ResolveProperty, import { InjectRepository } from '@nestjs/typeorm'; import PiotrSokolinski changed the title Resolve property - TypeError: Cannot read property� NestJS TypeORM InjectRepository Cannot read property 'prototype' of undefined. 0. NestJs + TypeORM injected repository becomes undefined. 0.

When you import TypeOrmModule.forFeature(...) you also have to import TypeOrmModule.forRoot(...). But in a unit test, you probably don't want to work with your database but instead mock out all dependencies.

Your controller should not access the database directly, that's what the service is for. So if you want to test your controller and it only injects the service, you should only declare an AuthService mock and not import anything:

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

If you want to test your AuthService and it only injects the repository declare your mockRepository and leave everything else out.

Database, Nest uses TypeORM because it's the most mature Object Relational Mapper ( ORM) import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { User } from '. To automatically load entities, set the autoLoadEntities property of the Warning Event subscribers can not be request -scoped. EDIT2: My HttpErrorFilter also says: Cannot read property 'role' of undefined. NestJS TypeORM InjectRepository Cannot read property 'prototype' of undefined. 4.

TypeORM and NestJS - 绵阳斯懿新材料科技有限公司, NestJS TypeORM InjectRepository Cannot read property 'prototype' of undefined. Trying to unit test. Got following error: TypeError: Cannot read property� TypeError: Cannot read property 'joinColumns' of undefined. It works fine as soon as I remove my Getter & Setter and set the properties to public access and removing the underscore. But I want to keep Getters & Setters actually. user.entity.ts

Getting started with NestJS & TypeORM (+bonus NestJS Admin , NestJS is one of the most complete NodeJS Framework in the NodeJs ecosystem . It is based on May 28, 2019 Quentin Somerville 11 min read. thumbnail import { InjectRepository } from '@nestjs/typeorm'; import { DogRepository } from '. Then, to be able to manipulate this database, I will use an ORM. I chose typeorm, which is also written in Typescript and recommended by the nestJS developers. Add typeorm and pg to the dependencies of the project: yarn add @nestjs/typeorm typeorm pg. Create Dogs entity. Now let’s create the dogs table in your database.

Nestjs throws a TS2322 err using the examples - node.js - html, Service undefine Cannot read property 'saveFormJson' of undefined in Angular { InjectRepository } from '#nestjs/typeorm'; import { Repository } from 'typeorm';� ConsentService › should save a user TypeError: Cannot read property 'save' of undefined But if i use test() method from my custom repository (user.repository.ts) it works fine. It looks like UserService its defined and it uses my custom repository however, when I run the test it says that the repository is undefined.

Comments
  • Did you solve it somehow? I"m having the same issue
  • @alex88 yes. I recreated project and copied all old files to new. Seems like it was some typeorm bug.
  • In order to let more user benefit form your answer, could you provide more explanation please.
  • You saved me alive!
  • UserService injects repository and AuthService injects UserService. I tryed ur code but still getting same error.
  • Weird, typeorm is not involved at all in the controller test. What's the stacktrace of the error, where does it point to?
  • Have a look at this test for reference: github.com/kiwikern/shassi-nest/blob/master/src/auth/…
  • Its point to @InjectRepository(User) at at Object.getRepositoryToken
  • That's really weird. The actual UserService should never be instantiated when you unit test the AuthController or the AuthService with mocks.