|
| 1 | +import { |
| 2 | + Controller, |
| 3 | + Get, |
| 4 | + INestApplication, |
| 5 | + MiddlewareConsumer, |
| 6 | + Module, |
| 7 | +} from '@nestjs/common'; |
| 8 | +import { Test } from '@nestjs/testing'; |
| 9 | +import * as request from 'supertest'; |
| 10 | +import { ApplicationModule } from '../src/app.module'; |
| 11 | + |
| 12 | +const RETURN_VALUE = 'test'; |
| 13 | +const SCOPED_VALUE = 'test_scoped'; |
| 14 | +const WILDCARD_VALUE = 'test_wildcard'; |
| 15 | + |
| 16 | +@Controller() |
| 17 | +class TestController { |
| 18 | + @Get('test') |
| 19 | + test() { |
| 20 | + return RETURN_VALUE; |
| 21 | + } |
| 22 | + |
| 23 | + @Get('tests/wildcard_nested') |
| 24 | + wildcard_nested() { |
| 25 | + return RETURN_VALUE; |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +@Module({ |
| 30 | + imports: [ApplicationModule], |
| 31 | + controllers: [TestController], |
| 32 | +}) |
| 33 | +class TestModule { |
| 34 | + configure(consumer: MiddlewareConsumer) { |
| 35 | + consumer |
| 36 | + .apply((req, res, next) => res.send(WILDCARD_VALUE)) |
| 37 | + .forRoutes('tests/*') |
| 38 | + .apply((req, res, next) => res.send(SCOPED_VALUE)) |
| 39 | + .forRoutes(TestController) |
| 40 | + .apply((req, res, next) => res.send(RETURN_VALUE)) |
| 41 | + .forRoutes('*'); |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +describe('Middleware', () => { |
| 46 | + let app: INestApplication; |
| 47 | + |
| 48 | + beforeEach(async () => { |
| 49 | + app = (await Test.createTestingModule({ |
| 50 | + imports: [TestModule], |
| 51 | + }).compile()).createNestApplication(); |
| 52 | + |
| 53 | + await app.init(); |
| 54 | + }); |
| 55 | + |
| 56 | + it(`forRoutes(*)`, () => { |
| 57 | + return request(app.getHttpServer()) |
| 58 | + .get('/hello') |
| 59 | + .expect(200, RETURN_VALUE); |
| 60 | + }); |
| 61 | + |
| 62 | + it(`forRoutes(TestController)`, () => { |
| 63 | + return request(app.getHttpServer()) |
| 64 | + .get('/test') |
| 65 | + .expect(200, SCOPED_VALUE); |
| 66 | + }); |
| 67 | + |
| 68 | + it(`forRoutes(tests/*)`, () => { |
| 69 | + return request(app.getHttpServer()) |
| 70 | + .get('/tests/wildcard') |
| 71 | + .expect(200, WILDCARD_VALUE); |
| 72 | + }); |
| 73 | + |
| 74 | + afterEach(async () => { |
| 75 | + await app.close(); |
| 76 | + }); |
| 77 | +}); |
0 commit comments