Exploring NestJS Controller Middleware Testing

After successfully implementing a middleware that checks query params against a regex pattern, I encountered some issues with integrating it into my unit tests. The middleware either calls next() if there are no issues or next(Error) if there is an issue.

export class ValidateRegistrationMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: NextFunction){
    let reg = new RegExp('^[A-Z0-9 _]*$');
    if (reg.test(req.params.registration)) {
        next()
    } else {
        next(new InvalidRegistrationException('Invalid Registration :' + req.params.registration, HttpStatus.BAD_REQUEST));
    }
}

}

To implement the middleware properly and use it in my tests, I had to configure it within the module component class.

@Module({
controllers: [MyController],
providers: [MyService]
})
export class MyModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(ValidateRegistrationMiddleware).forRoutes({
     path: 'service/:registration',
     method: RequestMethod.GET
     })
  }}

While this setup worked well for the application, I struggled to ensure the middleware ran before every test in the controller. I tried setting up the module in the beforeEach block of my spec file, but couldn't figure out how to include the middleware. Since the middleware was configured inside the module class, not as a decorator in the actual module, I faced this challenge.

beforeEach(async () => {

const module: TestingModule = await Test.createTestingModule({
  controllers: [MyController],
  providers: [MyService],
}).compile();

controller = module.get<MyController>(MyController);
service = module.get<MyService>(MyService);

});

If you have any suggestions on how to make the middleware run before each test in a controller, especially when testing invalid registration scenarios, please share your insights as the current setup doesn't trigger the middleware as expected.

Answer №1

When working with the testing module, it's important to ensure that your middleware setup is properly defined within the MyModule component.

If you encounter issues, consider importing MyModule to initialize your middleware configuration correctly.

See the example below for guidance:

beforeEach(async () => {

  const module: TestingModule = await Test.createTestingModule({
    imports: [MyModule],
  }).compile();

  controller = module.get<MyController>(MyController);
  service = module.get<MyService>(MyService);

});

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

Is it possible to utilize a variable within the 'has-text()' function during playwright testing?

With Playwright, I am attempting to locate an element based on the value of a variable For instance: let username = 'Sully' await page.click(`li:has-text(${username})`) However, I encounter the following error: page.click: Error: "has-tex ...

Leverage the Angular 2 router for sending varying values to a single component

The issue lies in the fact that the code provided below for the component AppComponent remains constant across three different routes: /, /route2, and /route3. The problem arises as the properties title and bodyHTML of the AppComponent do not update with ...

What is the process of incorporating an Auto-increment field for previously added records in MongoDB by utilizing the Mongoose-sequence

I successfully implemented auto-increment functionality for my MongoDB collection. Now, I am facing a challenge in adding this feature to the existing records within the database. Specifically, I am aiming to incorporate an auto-incrementing project_id fi ...

Is it feasible to securely remove an item from an array within an object without the need for any assertions in a single function?

My interest in this matter stems from curiosity. The title may be a bit complex, so let's simplify it with an example: type ObjType = { items: Array<{ id: number }>; sth: number }; const obj: ObjType = { sth: 3, items: [{ id: 1 }, { id: 2 } ...

Unexpected absence of req.body in get request but present in post request when utilizing axios and multer

Having an issue with my axios requests in a React app where the req.body in Express is undefined for a login (get) request, even though everything seems to be identical with the registration (post) request. Here is how I am sending the axios requests from ...

Combining arrays of objects sharing a common key yet varying in structure

Currently, I am facing a challenge while working on this problem using Typescript. It has been quite some time since I started working on it and I am hoping that the helpful community at StackOverflow could provide assistance :) The scenario involves two ...

Struggling to add an object to my Topic array using push

I'm in the process of developing a forum platform. Below is my Topic schema: const topicSchema = new mongoose.Schema({ author: { type: String, ref: "User", // Reference to the user who created the Topic required: true, }, t ...

Testing the retrieval of a file using Jest in an express controller

I recently implemented a basic Express endpoint for users to download a csv file. Now, I'm looking to write a test using Jest specifically for this file download endpoint. However, I'm a bit uncertain about which function or mock I should utiliz ...

What could be causing NestJS/TypeORM to remove the attribute passed in during save operation?

Embarking on my Nest JS journey, I set up my first project to familiarize myself with it. Despite successfully working with the Organization entity, I encountered a roadblock when trying to create a User - organizationId IS NULL and cannot be saved. Here ...

Retrieving information from the database and transferring it to the front end via the router

I have been working on a MERN Expo app login and sign-in page. However, I am facing an issue with fetching data from the backend after clicking the sign-in button. Even though I have implemented the find query in the Express router, I am unable to retrieve ...

Problem with sorting when using $in operator in MongoDB

I am looking to retrieve documents from a MongoDB collection where the IDs match those in an array: [ '5f80a44d0179262f7c2e6a42', '5f8c00762fae890e9c4d029c', '5f802cf8abac1116a46bf9d4' ] The problem arises when the docu ...

The behavior of an Angular 2 method varies depending on whether it is called in ngOnInit or triggered by a button

In the process of constructing a website with the Angular 2 CLI, I have encountered a perplexing issue. Specifically, I am working on a page that features a reactive form and have developed a method named addQuestion() that is invoked within the ngOnInit l ...

Mongodb Atlas Express.js Issue: Unable to Resolve Host Address

I am facing an issue connecting my express app to my mongoDb Atlas cluster. Due to sanctions on cloud databases in Iran, I use a VPN to practice. Can anyone help me identify if there is a coding mistake causing the error or if it's because of the VPN? ...

The issue persists with the addEventListener function not working multiple times

My issue is that the addEventListener function is only working for the 'scroll' event and not for 'addMoreFields' or 'removeFields'. If I move the scroll section down, then it works for 'addMoreFields' and 'remo ...

Troubles with Azure Blob Storage arise when trying to upload larger files using .uploadStream()

I am currently enhancing the functionality to upload larger files to Azure Blob Storage using Express.js and the @azure/storage-blob package. My current setup works well for files under 5mb, but anything larger seems to "fail" during the upload process. T ...

I am experiencing difficulty accessing other files from my index page in Express

After uploading my index.pug page on cloud9, I encountered an issue where I could access the page correctly using (appname).c9users.io/. However, when trying to include external CSS and JS files that were located in the same folder as my index.pug page, I ...

Confusion surrounding JWT authorization middleware

After reviewing the authentication middleware code in a course I am currently taking, I have some concerns about its security. I decided to test a protected route using Postman and discovered that I was able to retrieve an order for one user with a token ...

Unique text: "Singleton React component"

A counter component has been implemented using a npm package available here. import * as React from 'react'; import { Theme, createStyles, withStyles, WithStyles } from '@material-ui/core'; import withRoot from '../../../withRoot&a ...

In TypeScript, a generic function with an index constraint

Is it possible to define an element that operates in the manner indicated here? function fn<T, U extends keyof T, T[U] extends number>() I am having trouble making the "T[U] extends number" portion function correctly. ...

Enhance your Fastify routes by incorporating Swagger documentation along with specific tags and descriptions

Currently, I am utilizing fastify 3.28.0 in conjunction with the fastify-swagger plugin and typescript 4.6.2. My goal is to include tags, descriptions, and summaries for each route. As per the documentation found here, it should be possible to add descrip ...