|
| 1 | +import { NotFoundException } from '@nestjs/common'; |
| 2 | +import { Request, Response } from 'express'; |
| 3 | +import { ApiConfigService } from 'src/common/api-config/api.config.service'; |
| 4 | +import { RestrictedRoutesMiddleware } from 'src/utils/restricted.routes.middleware'; |
| 5 | + |
| 6 | +describe('RestrictedRoutesMiddleware', () => { |
| 7 | + let middleware: RestrictedRoutesMiddleware; |
| 8 | + let apiConfigService: jest.Mocked<ApiConfigService>; |
| 9 | + |
| 10 | + beforeEach(() => { |
| 11 | + apiConfigService = { |
| 12 | + getRestrictedRoutes: jest.fn(), |
| 13 | + } as unknown as jest.Mocked<ApiConfigService>; |
| 14 | + |
| 15 | + middleware = new RestrictedRoutesMiddleware(apiConfigService); |
| 16 | + }); |
| 17 | + |
| 18 | + it('should throw NotFoundException when route is restricted', () => { |
| 19 | + apiConfigService.getRestrictedRoutes.mockReturnValue(['/blocked']); |
| 20 | + |
| 21 | + const req = { |
| 22 | + path: '/blocked', |
| 23 | + } as Request; |
| 24 | + const res = {} as Response; |
| 25 | + const next = jest.fn(); |
| 26 | + |
| 27 | + expect(() => middleware.use(req, res, next)).toThrow(NotFoundException); |
| 28 | + expect(() => middleware.use(req, res, next)).toThrow('Cannot GET /blocked'); |
| 29 | + expect(next).not.toHaveBeenCalled(); |
| 30 | + }); |
| 31 | + |
| 32 | + it('should call next when route is not restricted', () => { |
| 33 | + apiConfigService.getRestrictedRoutes.mockReturnValue(['/blocked']); |
| 34 | + |
| 35 | + const req = { |
| 36 | + path: '/allowed', |
| 37 | + } as Request; |
| 38 | + const res = {} as Response; |
| 39 | + const next = jest.fn(); |
| 40 | + |
| 41 | + middleware.use(req, res, next); |
| 42 | + |
| 43 | + expect(next).toHaveBeenCalledTimes(1); |
| 44 | + }); |
| 45 | +}); |
0 commit comments