All checks were successful
Deploy to Test Environment / deploy-to-test (push) Successful in 26m51s
53 lines
1.5 KiB
TypeScript
53 lines
1.5 KiB
TypeScript
// src/tests/utils/createTestApp.ts
|
|
import express, { type Router, type RequestHandler } from 'express';
|
|
import type { Logger } from 'pino';
|
|
import { errorHandler } from '../../middleware/errorHandler';
|
|
import { mockLogger } from './mockLogger';
|
|
import type { UserProfile } from '../../types';
|
|
|
|
// Augment the Express Request type to include our custom `log` and `user` properties.
|
|
// This uses the modern module augmentation syntax instead of `namespace`.
|
|
declare module 'express-serve-static-core' {
|
|
interface Request {
|
|
log: Logger;
|
|
user?: UserProfile;
|
|
}
|
|
}
|
|
interface CreateAppOptions {
|
|
router: Router;
|
|
basePath: string;
|
|
authenticatedUser?: UserProfile;
|
|
middleware?: RequestHandler[];
|
|
}
|
|
|
|
/**
|
|
* Creates a standardized Express application instance for integration tests.
|
|
* It includes JSON parsing, a mock logger, an optional authenticated user,
|
|
* the specified router, and the global error handler.
|
|
*/
|
|
export const createTestApp = ({
|
|
router,
|
|
basePath,
|
|
authenticatedUser,
|
|
middleware = [],
|
|
}: CreateAppOptions) => {
|
|
const app = express();
|
|
app.use(express.json({ strict: false }));
|
|
|
|
// Apply custom middleware (e.g. cookieParser)
|
|
if (middleware.length > 0) {
|
|
app.use(middleware);
|
|
}
|
|
|
|
// Inject the mock logger and authenticated user into every request.
|
|
app.use((req, res, next) => {
|
|
req.log = mockLogger;
|
|
if (authenticatedUser) req.user = authenticatedUser;
|
|
next();
|
|
});
|
|
|
|
app.use(basePath, router);
|
|
app.use(errorHandler);
|
|
return app;
|
|
};
|