Nest.js: initializing properties from a superclass in a controller

I have a question about unit testing controllers in the Nest.js framework. My issue is that the property from a superclass is not initialized in the controller class when creating a test module.

Here is an example of the code I am referring to:

export class MyController extends SomeOtherController {

    // Inherited from SomeOtherController
    async initSomeObject() {
        this.someObject = await initializeThisSomehow();
    }

    async controllerMethod(args: string) {
        // Do something
    }

}

export abstract class SomeOtherController implements OnModuleInit {

    protected someObject: SomeObject;

    async onModuleInit() {
        await this.initSomeObject();
    }

    abstract async initSomeObject(): Promise<void>;
}

And here is how I set up my test:

describe('MyController', () => {
  let module: TestingModule;
  let controller: MyController;
  let service: MyService;

  beforeEach(async () => {
    module = await Test.createTestingModule({
      imports: [],
      controllers: [MyController],
      providers: [
        MyService,
        {
          provide: MyService,
          useFactory: () => ({
            controllerMethod: jest.fn(() => Promise.resolve()),
          }),
        },
      ],
    }).compile();

    controller = module.get(MyController);
    service = module.get(MyService);
  });

  describe('controller method', () => {
    it('should do something', async () => {
      jest.spyOn(service, 'controllerMethod').mockImplementation(async _ => mockResult);
      expect(await controller.controllerMethod(mockArgs)).toBe(mockResult);
    });
  });
});

While the application works fine in development mode with the someObject property being initialized, it does not work during tests as the test module seems to fail to initialize it (resulting in it being undefined).

Any assistance you can provide would be greatly appreciated.

Answer №1

Prior to each test in your suite, it is important to execute the following code:

await module.initialize(); // this triggers the onModuleInitialize function

Additionally, it is recommended to shut down the application after each test case.

afterEach(async () => await module.shutdown());

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

Guide to changing the border color in a Material-UI TextField component styled with an outline design

To complete the task, utilize the Material UI outlined input field (TextField component from "@material-ui/core": "^4.12.2",) and apply a custom blue color style to it. Here is the outcome of my work: https://i.sstatic.net/lw1vC.png C ...

utilize ng-bind to apply numerous values simultaneously

Is it possible to bind multiple values using ng-bind in the following manner : <p ng-bind="instructor.first_name instructor.last_name"></p> Every time I attempt this, I encounter the following error: Error: $parse:syntax Syntax Error I am a ...

Is it possible to convert an array into an object?

I'm attempting to restructure an array of objects into a new object where the label property serves as the key for multiple arrays containing objects with that same label. Check out this JSBin function I created to map the array, but I'm unsure ...

Setting up grunt-ts to function seamlessly with LiveReload

I am currently experimenting with using TypeScript within a Yeoman and Grunt setup. I've been utilizing a Grunt plugin called grunt-ts to compile my TypeScript files, and while the compilation process is smooth, I'm encountering issues with live ...

Can anyone provide guidance on incorporating jQuery typing into an angular2 seed project?

I'm struggling to incorporate jQuery typings into my Angular2-seed project. Within my component, I am utilizing jQuery in the following manner: declare let $: any; export class LeafletComponent implements OnInit { ngOnInit(): void { th ...

A guide to reordering table rows by drag-and-drop with JavaScript

Seeking assistance with swapping table rows using JQuery UI. Although successful in the swap, struggling to retrieve row numbers during the drag and drop event. Understanding the row number is essential for subsequent tasks. Any help would be greatly appre ...

What is the method to reach a named parameter within a function?

Currently, I am building a RESTful web service using Node JS in combination with Backbone JS. Within this service, there is a specific REST method called GET /users/id/:id, where :id represents the user's identification number. The purpose of this met ...

What is the most effective method to patiently anticipate a specific duration for a function's output?

I am faced with a situation where I have two functions at hand. One function performs complex logic, while the other wraps this function to provide either the result of computation or an error message after a specified amount of time t. Consider the follo ...

Customize numbers in JavaScript with a Unity-inspired design changer

I am currently working on implementing a number input feature that allows users to adjust values by clicking and holding the mouse button while moving the cursor left and right, similar to Unity's editor number adjuster: https://youtu.be/uY9PAcNMu8s?t ...

Angular Persistent States in Angular version 2 and beyond

Currently, I am in the process of transitioning an Angular 1.5.X application to Angular 4. Within my app, I incorporate Angular Ui-Router Sticky State from https://github.com/ui-router/sticky-states to prevent loss of content within my view when navigating ...

Transforming Uint8Array into BigInt using Javascript

I've come across 3 different ways to convert a Uint8Array to BigInt, but each method seems to produce varying results. Can someone clarify which approach is correct and recommended? Utilizing the bigint-conversion library. The function bigintConversi ...

FullCalendar fails to load in Bootstrap 4 tab

My current project involves utilizing Bootstrap 4 tabs, and I encountered an issue with displaying a FullCalendar on the second tab. Specifically, I am using version 5.2.0 of the FullCalendar library. While the calendar functions correctly when placed on t ...

Is the 404 page being utilized as a fallback for AJAX requests?

I am looking to create a one-page website that utilizes history.pushstate to modify the URL. My plan involves having only one HTML file for the site, which would be the 404 error page. This setup would redirect users to that page regardless of the URL they ...

Issue with jQuery click event not activating on initial click but functioning properly on the subsequent click

I am currently implementing the jquery.ime editor in my project, which allows for multi-language editing capabilities. The library I am using can be found here. By default, the language JSON files are loaded on "change" events. However, I would like this f ...

tips for uploading image data using JavaScript

My HTML form sends POST data to my PHP script and uses AJAX for a live preview The issue arises with the image input field in the form Here's an example of the form structure: <form method="post" action="scripts/test.php" enctype="multipart/form ...

React 17 Form not registering the final digit during onChange event

I am currently experiencing an issue with a form that includes an input field of type "number." When I enter a value, the last number seems to be skipped. For example: If I input 99 into the box, only 9 is saved. Similarly, when typing in 2523, only 252 ...

Allow Microsoft OAuth authentication for web applications only, restricting access to other Microsoft services

I am currently integrated Firebase into my website, allowing users to sign in using their Microsoft accounts through OAuth 2.0: import {getAuth, signInWithRedirect, OAuthProvider} from "firebase/auth"; (...) const provider = new OAuthProvider(& ...

What defines a suitable application of the ref feature in React?

How can the ref attribute be effectively used in React? I understand that it is considered a shortcut that may go against the principles of React DOM, but I want to know the specifics of how and why. I'm currently evaluating if my use case justifies t ...

Circular arrangement using D3 Circle Pack Layout in a horizontal orientation

I'm currently experimenting with creating a wordcloud using the D3 pack layout in a horizontal format. Instead of restricting the width, I am limiting the height for my layout. The pack layout automatically arranges the circles with the largest one ...

Customized Error Handling Function for Ajax Requests

I have a function that works perfectly, but I need to add six more buttons without repeating code. I want each callback to be customizable, with different text for each scenario (e.g. displaying "Please Log In" if the user is not an admin). How can I make ...