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

What is the best way to send an array of locationIds to the getLocationData service?

Seeking Assistance on Sending an Array of Location IDs to a Service I currently have an array consisting of location IDs. locationArr=[40871, 60009, 38149, 40868, 43240, 15299, 53897, 40976, 38151, 23183, 38152, 78579, 23180, 40977, 23176, 39565, 40884, ...

Exploring the versatility of Vue.js through props and scoped slots

Coming from a React background, I am used to being able to easily alter children components before they render. However, after spending hours reading the VueJS documentation and searching forums, I have not been able to find a straightforward way to do thi ...

Tips for setting up Material-UI with create-react-app for proper testing

I have created a sample based on the material-ui Testing page. The application was built using create-react-app and I have included enzyme in my project. import { createMount } from '@material-ui/core/test-utils'; import MyComponent from '. ...

The library path in a react (js) integrated mono repo could not be resolved by Nx 16

Greetings everyone, I am a newcomer to the world of NX Monorepo. Following the step-by-step instructions on how to create an Integrated React Monorepo from the official NX website can be found here. I diligently followed each instruction provided. Howeve ...

How can React TypeScript bind an array to routes effectively?

In my project, I am using the standard VisualStudio 2017 ASP.NET Core 2.0 React Template. There is a class Home included in the template: import { RouteComponentProps } from 'react-router'; export class Home extends React.Component<Rout ...

Tips for defining types for specific CSS properties in TypeScript, such as variables

Perhaps there are already solutions out there, and I appreciate it if you can share a link to an existing thread. Nevertheless... In React, when I use the style prop, I receive good autocompletion and validation features like this example: What am I look ...

Troubleshooting: The canvas texture in Phaser 3's Update() function is not functioning

I've been attempting to transform this tutorial into Phaser 3: but have encountered an issue with the update() function not working. I also tried using the refresh() function, but that didn't solve the problem either. In my file a.ts, I have cre ...

What happens when Angular elements don't have an injector?

Exploring Angular's custom elements while steering clear of dependency injection is my current experiment. const MyElementElement = createCustomElement(MyElementComponent, { injector }); customElements.define('my-element', MyElementElement) ...

employing a variable within a function that is nested within another function

I'm encountering an issue where I am using a variable within a nested function. After assigning a value to it, I pass it to the parent function. However, when I call the function, nothing is displayed. function checkUserExists(identifier) { let user ...

What methods are available for altering state in Server Actions in NextJS 13?

Struggling to Implement State Change in NextJS 13 Server Actions I have encountered a challenge with altering state within the execution of server actions in NextJS 13. The scenario involves an actions.ts file located at the root of the app directory. Cur ...

The 'wrapper' property is not present in the 'ClassNameMap<never>' type in Typescript

Hey there, I've been encountering a puzzling issue in my .tsx file where it's claiming that the wrapper doesn't exist. My project involves Material UI and Typescript, and I'm relatively new to working with Typescript as well as transiti ...

What is the best way to transfer information from the window method to the data function in a Vue.js application?

Is there a way to transfer information from the window method to the data function in a vuejs component? Take a look at my window method: window.authenticate = function(pid, receiptKey) { console.log("Authentication"); console.log(this) localStorag ...

Reasons behind Angular HttpClient sorting JSON fields

Recently, I encountered a small issue with HttpClient when trying to retrieve data from my API: constructor(private http: HttpClient) {} ngOnInit(): void { this.http.get("http://localhost:8080/api/test/test?status=None").subscribe((data)=> ...

When using Jest, the mongoose findOneAndUpdate function may return null values for both error and document

I've been struggling with Mongoose's findOneAndUpdate method as it doesn't seem to provide any useful information. I have tried accessing the Query returned from calling it (stored in updatedUser), but all it returns is null. Adding a callba ...

"Learn the trick of converting a stream into an array seamlessly with RxJs.toArray function without the need to finish the

In order to allow users to filter data by passing IDs, I have created a subject that can send an array of GUIDs: selectedVacancies: Subject<string[]> = new Subject(); selectedVacancies.next(['a00652cd-c11e-465f-ac09-aa4d3ab056c9', ...

Encountering Invalid Chai attribute: 'calledWith'

I am currently in the process of implementing unit tests for my express application. However, I encountered an error when running the test: import * as timestamp from './timestamp' import chai, { expect } from 'chai' import sinonChai f ...

What is the purpose of importing a module in app.module.ts? And what specifically happens when importing classes one by one in the

I am interested in creating an Angular form, but I have a question about why we import 'ReactiveFormsModule' in app.module. Additionally, I am curious as to why we need to explicitly import classes like FormControl and FormGroup again in the temp ...

Unable to locate the specified nested module during the import process

Imagine a scenario where we have two packages, namely package1 and package2. When package2 attempts to import the module from package1, an error is thrown stating that the module is not found. The import statement in question looks like this: import { ... ...

Tips for creating a deepCss selector for an input Textbox in Protractor

When I attempt to use sendKeys in an input textbox with Protractor, the element is located within a shadow-root and there are three separate input textboxes. ...

What are the steps to retrieve a Json Object from an Array while extracting information from Rapid API?

Utilizing axios to fetch data from a GET API on RapidAP returns an array of JSON objects, as illustrated in the images below. How can I implement Typescript within React to specifically extract the data of these JSON objects from the array according to my ...