|
| 1 | +import { INestApplication, MiddlewareConsumer, Module } from '@nestjs/common'; |
| 2 | +import { Test } from '@nestjs/testing'; |
| 3 | +import * as request from 'supertest'; |
| 4 | + |
| 5 | +const RETURN_VALUE_A = 'test_A'; |
| 6 | +const RETURN_VALUE_B = 'test_B'; |
| 7 | + |
| 8 | +@Module({ |
| 9 | + imports: [], |
| 10 | +}) |
| 11 | +class TestAModule { |
| 12 | + configure(consumer: MiddlewareConsumer) { |
| 13 | + consumer |
| 14 | + .apply((req, res, next) => { |
| 15 | + res.send(RETURN_VALUE_A); |
| 16 | + }) |
| 17 | + .forRoutes('hello'); |
| 18 | + } |
| 19 | +} |
| 20 | + |
| 21 | +@Module({ |
| 22 | + imports: [TestAModule], |
| 23 | +}) |
| 24 | +class TestBModule { |
| 25 | + configure(consumer: MiddlewareConsumer) { |
| 26 | + consumer |
| 27 | + .apply((req, res, next) => { |
| 28 | + res.send(RETURN_VALUE_B); |
| 29 | + }) |
| 30 | + .forRoutes('hello'); |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +@Module({ |
| 35 | + imports: [TestBModule], |
| 36 | +}) |
| 37 | +class TestModule { |
| 38 | +} |
| 39 | + |
| 40 | +describe('Middleware Execute Order', () => { |
| 41 | + let app: INestApplication; |
| 42 | + |
| 43 | + beforeEach(async () => { |
| 44 | + app = (await Test.createTestingModule({ |
| 45 | + imports: [TestModule], |
| 46 | + }).compile()).createNestApplication(); |
| 47 | + |
| 48 | + await app.init(); |
| 49 | + }); |
| 50 | + |
| 51 | + it(`Execute middleware of dependent modules first `, () => { |
| 52 | + return request(app.getHttpServer()) |
| 53 | + .get('/hello') |
| 54 | + .expect(200, RETURN_VALUE_A); |
| 55 | + }); |
| 56 | + |
| 57 | + afterEach(async () => { |
| 58 | + await app.close(); |
| 59 | + }); |
| 60 | +}); |
0 commit comments