My tests are unable to execute on the test database due to the lack of a defined service

I am currently trying to execute my test file in NestJS. My goal is to connect to a test database and run my service with it. However, I am facing an issue where my service is undefined and the method service.findById is also undefined. How can I obtain an instance of the UserService in my test file?

user.service.ts


import { Injectable } from '@nestjs/common';
import { User } from './model/user.model';
import { InjectModel } from '@nestjs/sequelize';

@Injectable()
export class UserService {
  constructor(
    @InjectModel(User)
    private userModel: typeof User,
  ) {}

  async findById(id: number): Promise<User> {
    return await this.userModel.findOne({
      where: { id },
      raw: true,
      nest: true,
    });
  }
}

user.service.spec.ts


import { Test, TestingModule } from '@nestjs/testing';
import { UserService } from './user.service';
import { SequelizeModule } from '@nestjs/sequelize';

describe('UserService', () => {
  let service: UserService;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      imports: [
        SequelizeModule.forRoot({
          dialect: 'postgres',
          host: 'localhost',
          port: 5432,
          username: 'postgres',
          password: '@@@',
          database: 'test',
        }),
      ],
      providers: [UserService],
    }).compile();

    service = module.get<UserService>(UserService);
  });

  it('should be defined', () => {
    expect(service).toBeDefined();
  });

  it('should return id', async () => {
    const user = await service.findById(1)
    expect(user.id).toBeDefined();
  });
});

Answer №1

Are you experiencing what is known as the dreaded path confusion dilemma? Yes, you heard that right. This occurs when attempting to initialize a class, like UserService, only to realize it has a dependency on User within its constructor. The issue arises when User cannot be accessed from the location of your user.service.spec.ts file due to the relative path used in the

import { User } from './model/user.model';
statement.

You may find useful insights in this article (disclaimer: I did not write it) that delves into various npm packages which offer potential solutions to this dilemma here.

Answer №2

Initially, the reason service is showing as undefined is due to the fact that module.get is only capable of accessing exported providers. Therefore, it becomes necessary to export UserService:

const module: TestingModule = await Test.createTestingModule({
  imports: [
    SequelizeModule.forRoot({
      //...
    }),
  ],
  providers: [UserService],
  exports: [UserService],
}).compile();

Moreover, Nestjs provides a clear error message:

Nest can't resolve dependencies of the UserService (?, UserNavigationService). Please make sure that the argument UserRepository at index [0] is available in the RootTestModule context.

This clearly indicates that UserRepository was not found within the testing module and consequently, UserService, which relies on it, could not be initialized. In order to rectify this issue, the repository needs to be added to the testing module:

const module: TestingModule = await Test.createTestingModule({
  imports: [
    SequelizeModule.forRoot({
      //...
    }),
    // Ensure the User repository is accessible within the module.
    SequelizeModule.forFeature([User]),
  ],
  //...
}).compile();

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

Exploring the realm of Typescript custom decorators: The significance behind context

I'm currently working on a custom decorator that will execute decorated functions based on RxJS events. Everything seems to be going well so far, but I'm facing an issue when the function is executed: the context of the this object is lost. I&a ...

What is the correct way to include a JSON file in TypeScript?

Currently, I'm attempting to reference a JSON path and save it as a constant. My initial approach involved creating a reference with a string and then sending it back as a response using res.send, which successfully returned the string. However, I am ...

Is it possible to implement lazy loading for data in TypeScript classes?

Looking to optimize my Angular application's data structure when consuming a RESTful API. My goal is to only load necessary data from the server on demand. For instance, if I have a collection of Building objects each with a set of tenant IDs in an a ...

Issue when transferring properties of a component to a component constructed Using LoadingButton MUI

Check out my new component created with the LoadingButton MUI: view image description here I'm having issues passing props to my component: view image description here Dealing with a TypeScript problem here: view image description here I can resolv ...

Need for utilizing a decorator when implementing an interface

I am interested in implementing a rule that mandates certain members of a typescript interface to have decorators in their implementation. Below is an example of the interface I have: export interface InjectComponentDef<TComponent> { // TODO: How ...

Prevent receiving the "deprecated warning for current URL string parser" by enabling the useNewUrlParser option

I recently encountered an issue with my database wrapper class that connects to a MongoDB instance: async connect(connectionString: string): Promise<void> { this.client = await MongoClient.connect(connectionString) this.db = this.cli ...

Retrieving information stored in a FormBuilder through the HTML

Once I set up a FormBuilder during the onInit Lifecyle: surveyForm: FormGroup; ngOnInit(): void { this.surveyForm = this.formBuilder.group({ 'surveyTitle': new FormControl(null), 'surveyDescription': new FormControl(n ...

Encountering a problem with an InvalidPipeArgument in Angular 6

Here's a quick summary of the situation: I recently upgraded my application to the latest version of Angular, moving from 5 to 6. All deployments in the packages.json file were updated using the ng update command. In my application, I save a Date() ...

What could be causing the issue of CSS Styles not being applied to an Angular 2 component with Vaadin elements?

Currently, I am immersed in the tutorial on Vaadin elements using Angular 2 that I stumbled upon here In section 5.3, Styles are applied to the app.component.ts as shown below import { Component } from [email protected]/core'; @Component({ select ...

Injecting Variables Into User-Defined Button

Presenting a custom button with the following code snippet: export default function CustomButton(isValid: any, email: any) { return ( <Button type="submit" disabled={!isValid || !email} style={{ ...

Is there a way to modify the style within a TS-File?

I've created a service to define different colors and now I want to set separate backgrounds for my columns. However, using the <th> tag doesn't work because both columns immediately get the same color. Here's my code: color-variatio ...

Encountering a Typescript issue when trying to access props.classes in conjunction with material-ui, react-router-dom

I could really use some help with integrating material-ui's theming with react-router-dom in a Typescript environment. I'm running into an issue where when trying to access classes.root in the render() method, I keep getting a TypeError saying &a ...

The scope of the inferred type parameter in the generic TypeScript function is overly broad

I'm currently working on creating a function that takes in another function (a React component) as an argument and then returns a related function. My goal is to define specific requirements for the input function, ensuring that it accepts certain pr ...

Is it possible that React.createElement does not accept objects as valid react children?

I am working on a simple text component: import * as React from 'react' interface IProps { level: 't1' | 't2' | 't3', size: 's' | 'm' | 'l' | 'xl' | 'xxl', sub ...

What methods can TypeScript employ to comprehend this situation?

There's an interesting scenario when it comes to assigning a variable of type unknown to another variable. TypeScript requires us to perform type checking on the unknown variable, but how does TypeScript handle this specific situation? It appears that ...

What is the best way to iterate over a nested array of objects and render them in my HTML using Angular/Ionic?

One of the challenges I'm facing involves working with an interface structured like this: export interface SeriesCard { type: string, imageUrl: string, title: string, category: string, seriesItems: SeriesItems[]; } Currently, my Service con ...

"Elaborate" Typescript Conditional Generic Types

Scenario I am currently working on implementing strong typing for the onChange function of a UI library's Select component. To provide some context, the existing type definition for their onChange is as follows: onChange?: (...args: any[]) => v ...

Stop MatDialog instance from destroying

In my application, I have a button that triggers the opening of a component in MatDialog. This component makes API calls and is destroyed when the MatDialog is closed. However, each time I open the MatDialog for the second time by clicking the button agai ...

Unable to access the `isDragging` property in TypeScript when using the `useDrag` method from react-d

As a newcomer to utilizing react in combination with typescript, I am currently working on implementing a drag and drop feature using the react-dnd package along with typescript. I came across this helpful blog that has guided me through the process of dra ...

Transforming a JSON object into XML format

Currently, I am encountering an issue while attempting to convert my JSON object to XML using the xml-js library's json2xml function. When trying to implement this functionality, I keep getting an error message that states: Error: Buffer is not defin ...