Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure middleware in e2e test in nestjs

In real app, we write:

export class AppModule implements NestModule {
  constructor() {}

  configure(consumer: MiddlewareConsumer) {
    consumer.apply(JwtExtractionMiddleware).forRoutes({
      path: 'graphql',
      method: RequestMethod.ALL,
    });
  }
}

In e2e test, I do something like this:

const module = await Test.createTestingModule({
  imports: [ GraphQLModule.forRoot(e2eGqlConfig) ],
  providers: [ PubUserResolver ],
}).compile();
app = await module.createNestApplication().init();

So how can I specific middleware in e2e test?

like image 525
JeffChan Avatar asked Sep 13 '18 14:09

JeffChan


2 Answers

Maybe try to create a specific TestModule class only for e2e and provide it to the createTestingModule?

@Module({
  imports: [ GraphQLModule.forRoot(e2eGqlConfig) ],
  providers: [ PubUserResolver ],
})
export class TestModule implements NestModule {
  constructor() {}

  configure(consumer: MiddlewareConsumer) {
    consumer.apply(JwtExtractionMiddleware).forRoutes({
      path: 'graphql',
      method: RequestMethod.ALL,
    });
  }
}

And then in e2e:

const module = await Test.createTestingModule({
  imports: [TestModule]
}).compile();
app = await module.createNestApplication().init();

I had similar problem, I needed to attach global middlewares. There is no info on the Internet about that as well, but by chance I've found the solution. Maybe someone will be looking for it, so here it is:

To use global middleware in e2e in NestJS:

Firstly create the app, but don't init it. Only compile:

const app = Test
  .createTestingModule({ imports: [AppModule] })
  .compile()
  .createNestApplication();

After that you can add all your global middlewares:

app.enableCors();
app.use(json());
app.use(formDataMiddleware(config));

Now init the app and that's it:

await app.init();
like image 75
hidook Avatar answered Nov 01 '22 05:11

hidook


You'll need to put app.use(new AuthMiddleware().use); before app.init().

describe('Module E2E', () => {
  const mockedTest = {
    create: jest.fn().mockImplementation((t) => Promise.resolve(t)),
  };

  let app: INestApplication;

  beforeAll(async () => {
    const moduleRef = await Test.createTestingModule({
      imports: [
        ConfigModule.forRoot({
          load: [configuration],
        }),
      ],
      controllers: [TestController],
      providers: [
        TestService, // the service contains a MySQL Model
        {
          provide: getModelToken(Test), // Test is the name of Model
          useValue: mockedTest,
        },
      ],
    }).compile();

    app = moduleRef.createNestApplication();
    app.use(new AuthMiddleware().use); // auth middleware
    await app.init();
  });
});
like image 4
user1455180 Avatar answered Nov 01 '22 06:11

user1455180