Issues with endpoints not functioning after importing a NESTJS module

Could someone please explain why the appController is functioning correctly while the itemsController, imported from a module, is not?

I have been learning NestJS and followed the documentation as instructed. The appController is working fine with its uncommented endpoint.

import {Controller, Get} from '@nestjs/common';
import { AppService } from './app.service';

@Controller()
export class AppController {
  constructor() {}
  
  // @Get()
  // getHome():string {
  //    return 'Hello world!';
  // }
  
}

The itemsController.ts - functions correctly if I swap it for appController.ts

import {Controller, Get, HttpException, HttpStatus, Param, Post, Res} from "@nestjs/common";
import {Response} from "express";
import {ItemsService} from "./items.service";
import {ItemDto} from "./dto/item.dto";

@Controller()

export class ItemsController {
    
    constructor(private readonly itemsService: ItemsService) {}
    
    @Get()
    getAll(@Res({passthrough: true}) res: Response):string | object {
        
        const items = this.itemsService.getAll();
        
        if(!!items.length) {
            res.status(HttpStatus.OK);
            return new HttpException({
                items: items
            }, HttpStatus.OK).getResponse();
        }
        
        res.status(HttpStatus.INTERNAL_SERVER_ERROR);
        
        return new HttpException({
            items: 'Items length: ' + items.length,
            status: HttpStatus.INTERNAL_SERVER_ERROR
        }, HttpStatus.INTERNAL_SERVER_ERROR).getResponse();
        
    }
    
    @Post()
    create(@Param() params):ItemDto {
        return this.itemsService.create(params);
    }
    
}

My Jest tests are also passing successfully:

import { Test } from '@nestjs/testing';
import { ItemsController } from './items/items.controller';
import { ItemsService } from './items/items.service';
import * as request from 'supertest';
import { INestApplication } from "@nestjs/common";

describe('ItemsModule', () => {
    let itemsController: ItemsController;
    let itemsService: ItemsService;
    let app: INestApplication;
    
    beforeEach(async () => {
        const moduleRef = await Test.createTestingModule({
            controllers: [ItemsController],
            providers: [ItemsService],
        }).compile();
        
        itemsService = moduleRef.get<ItemsService>(ItemsService);
        itemsController = moduleRef.get<ItemsController>(ItemsController);
        
        app = moduleRef.createNestApplication();
        await app.init();
    });
    
    describe('End-points', () => {
        
        it('/GET Status 200', () => {
            
            return request(app.getHttpServer())
                .get('/')
                .expect(200)
                .expect({
                    "items": [
                        {
                            id: '0',
                            title: '',
                            message: ''
                        }
                    ]
                });
            
        });
        
        it('/GET Status 500', () => {
            
            return request(app.getHttpServer())
                .get('/')
                .expect(500)
                .expect({
                    items: 'Items length: 0',
                    status: 500
                });
            
        });
    });
});

I have uploaded all the code on Github. You can view it here

Answer №1

Upon reviewing your code, it appears you need to include the @ symbol before @Module() in your ItemsModule

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

MUI-Datatable rows that can be expanded

I'm attempting to implement nested tables where each row in the main table expands to display a sub-table with specific data when clicked. I've been following the official documentation, but so far without success. Below is a code snippet that I& ...

What is the best way to input a value into the search bar within an Iframe?

I've created a basic website using node and a pug page where I inserted an iframe from wikipedia.com. My goal is to have the search input in the Wikipedia iframe populated with a value based on a button click within the same pug page. Is this feasible ...

How to add and append values to an array in a Realtime Database

My React.js app allows users to upload songs to Firebase and view the queue of uploaded songs in order. The queue can be sorted using a drag-and-drop system that updates the database in Firebase. Is there a way to insert these songs into an array when uplo ...

Merging two JSON objects in the absence of one

function fetchData(url) { return fetch(url).then(function(response) { return response.json(); }).then(function(jsonData) { return jsonData; }); } try { fetchData(`https://api.hypixel.net/skyblock/auctions?key=${apikey}`).the ...

Error caused by the shouldDisableDate prop in MUI DatePicker's functionality

<Controller name="toDate" control={control} defaultValue={null} render={({ field }) => ( <DatePicker format="DD/MM/yyyy" value={field.value} onChange={(e) => { setToDate(e); field.onC ...

Is there a way to retrieve all indices of an array?

Is there a way to retrieve all the index positions of the elements in an array? [ { "name":"aloha", "age":"18" }, { "name":"hello word" }, { "name":"John Doe", "age":"28" } ] The expected output sho ...

The javascript file is unable to detect the presence of the other file

I am facing an issue with two JavaScript files I have. The first one contains Vue code, while the other one includes a data array where I created the 'Feed' array. However, when trying to output a simple string from that array, the console throws ...

What is the mechanism behind AJAX functioning without the need to refresh the page?

I came across a code (not written by me) for a button that allows users to bookmark a person and add them to a shortlist. Here's how the code looks: Here is the JS & Ajax portion: self.isMarked = ko.observable(@(Model.Application.IsMarked ? "tru ...

Exclusive to Safari: Codesandbox is experiencing difficulties retrieving data from the localhost server

Would you mind helping me out with this technical issue I'm facing? For the server/API, I am using this link. As for the mock website, it can be found at this URL. The problem is that, in my code, I'm using axios to fetch data from the locally h ...

Using AngularJS, display content only if the JSON response is [false]

Recently, I started learning AngularJS and am currently working on a project where I need a div to only be visible when the JSON data returns [false]. Sometimes, the JSON does return [false] particularly when there are no results from the query. JavaScrip ...

What could be causing my jQuery code to not function properly?

I wrote a small piece of code in jQuery, but I am having trouble executing it. Can someone help me figure out what I'm doing wrong? <html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.min.js"> & ...

The ternary operator, also known as the conditional operator

One feature I have implemented is a button that can generate a random color and update the color state with this value. The color state is then used to define the background color of the div. Within the div, there is a lock/unlock button that toggles the ...

Is it possible to use async/await together with forEach in JavaScript?

Within my array of objects containing user information and emails, I aim to send emails using AWS SES. To accomplish this, I must decide between utilizing await or normal .then. Preferably, I would like to use await within a forEach loop. Is it feasible to ...

Exploring the wonders of nested jQuery $.when statements

My goal is to create the following code snippet: var async1 = $.when( a1() ).then(function(){ a2() }); var async2 = $.when( a3() ).then(function(){ a4() }); $.when(async1, async2).then(function(){ console.log("complete"); }); However, currently, wh ...

Animating CSS styles in Vue.js based on JavaScript triggers

Within my Vue.js application, I've implemented a login form that I'd like to shake whenever a login attempt fails. Though I have achieved the desired shaking effect, I'm not completely satisfied with my current solution. Here's a simpl ...

Encountering unexpected null values post-service invocation in Angular 2

I have encountered an issue in Angular 2 where a variable is returning undefined. The problem arises when a function calls a service to initialize a variable, which is then used in another function to make a get HTTP request. However, the get request fails ...

Assigning a prop value in Vue using JavaScript

I am currently facing a challenge with an old legacy MVC application that contains various UI technologies such as razor pages, jQuery, and Vue native components. The issue at hand is that although the new Vue components function perfectly in isolation, we ...

Managing jwt expiration in Single Page Applications

After receiving a JWT from the backend where even the public key is encrypted, I am left with only the encoded token. This token is appended to all of my app's http calls, but there are only 5 such calls - 4 get requests and 1 put request. The issue a ...

Stop a div at a specific point with this unique jQuery plugin

I am looking to implement a similar feature on my website that can be seen here: The desired functionality is when a link stops at a certain point while scrolling, and upon clicking the link it smoothly scrolls to a designated div. Additionally, as you sc ...

Utilizing the request body value within the .withMessage() function of the Express validator chain

I am looking to showcase my express validator errors with the specific value entered by the user. For instance, if a user types in an invalid username like "$@#" (using a regex that I will provide), I want to return my error message as follows : { "er ...