How to override authentication middleware in Nestjs testing?

139 Views Asked by At

I have an e2e test in a NestJS app where I would like to test a path which is protected by some authentication middleware.

import { Test, TestingModule } from '@nestjs/testing';
import { AppModule } from '../src/app.module';
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';

fdescribe('App health (e2e)', () => {
  let app: INestApplication;

  beforeEach(async () => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [AppModule],
    }).compile();

    app = moduleFixture.createNestApplication();
    await app.init();
  });


  // override authentication middleware should come here
  it('should fetch a doc which is not public', () => {
    return request(app.getHttpServer())
      .get('/some/protected/path')
      .expect(200)
  });


  afterAll(()=>{
    app.close()
  })
});

The auth middleware is activated through one of the modules in the app like so:

export class PagesModule {
  configure(consumer: MiddlewareConsumer): void {
    consumer
      .apply(UserMiddleware)
      .forRoutes({ path: '*', method: RequestMethod.ALL });
  }
}

Is there a way for me to override and replace this authentication middleware? Can I replace it only for a single test?

1

There are 1 best solutions below

0
Yaron On

Apparently this is still an open issue: https://github.com/nestjs/nest/issues/4073

But there's a workaround: To reoconfigure the testing module:

@Module({
  imports: [AppModule],
})
export class TestAuthOverride implements NestModule {
  constructor(){
  }
  configure(consumer: MiddlewareConsumer) {
    consumer.apply((req, res, next) => {
      //override here
      next();})
    .forRoutes({ path: '*', method: RequestMethod.ALL });
    
  }
}