diff --git a/__tests__/errorController.test.ts b/__tests__/errorController.test.ts index 04e5b39..a566d5b 100644 --- a/__tests__/errorController.test.ts +++ b/__tests__/errorController.test.ts @@ -1,7 +1,8 @@ +import app from '../server/index'; +import request from 'supertest'; import { Request, Response, NextFunction } from 'express'; -import { notFound } from '../server/controllers/errorControllers'; import errorHandler from '../server/middleware/errorHandler'; -import { BadRequestError } from '../server/errors'; +import { BadRequestError, NotFoundError } from '../server/errors'; describe('Middleware Tests', () => { let mockRequest: Partial; @@ -18,10 +19,13 @@ describe('Middleware Tests', () => { }); describe('notFound Middleware', () => { - it('should return 404 and the original URL', () => { - notFound(mockRequest as Request, mockResponse as Response, mockNext); - expect(mockResponse.status).toHaveBeenCalledWith(404); - expect(mockNext).toHaveBeenCalled(); + it('should return 404 and the original URL', async () => { + const exampleNotFoundError = new NotFoundError(); + + const response = await request(app).get('/non-existent-route').send(); + + expect(response.status).toEqual(404); + expect(response.body).toEqual(exampleNotFoundError.serializeErrors()); }); }); diff --git a/server/controllers/errorControllers.ts b/server/controllers/errorControllers.ts deleted file mode 100644 index 4c7b2ec..0000000 --- a/server/controllers/errorControllers.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { Request, Response, NextFunction } from 'express'; - -const notFound = (req: Request, res: Response, next: NextFunction): void => { - const error = new Error(`Not found - ${req.originalUrl}`); - res.status(404); - next(error); -}; - -export { notFound }; diff --git a/server/index.ts b/server/index.ts index 92cbfac..275a568 100644 --- a/server/index.ts +++ b/server/index.ts @@ -11,8 +11,8 @@ import devRoutes from './routes/devRoutes'; import connectDB from './config/db'; import dotenv from 'dotenv'; import cookieParser from 'cookie-parser'; -import { notFound } from './controllers/errorControllers'; import errorHandler from './middleware/errorHandler'; +import { NotFoundError } from './errors'; dotenv.config(); @@ -21,8 +21,6 @@ const app: Application = express(); app.use(express.json()); app.use(cookieParser()); -connectDB(); - app.get('/health', (req: Request, res: Response) => { res.status(200).send('OK'); }); @@ -49,13 +47,17 @@ if (process.env.NODE_ENV === 'production') { }); } -app.use(notFound); +app.use((_req, _res) => { + throw new NotFoundError(); +}); app.use(errorHandler); const PORT: number = Number(process.env.PORT) || 3000; export const startServer = () => { + connectDB(); + return app.listen(PORT, () => console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`), );