Skip to content

Commit

Permalink
fix(templates): test routes
Browse files Browse the repository at this point in the history
  • Loading branch information
harm-meijer committed Sep 16, 2024
1 parent e82c7ac commit a532cdd
Show file tree
Hide file tree
Showing 33 changed files with 519 additions and 194 deletions.
33 changes: 33 additions & 0 deletions application-templates/javascript/event/src/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import 'dotenv/config';

import express from 'express';
import bodyParser from 'body-parser';

// Import routes
import EventRoutes from './routes/event.route.js';

import { readConfiguration } from './utils/config.utils.js';
import { errorMiddleware } from './middleware/error.middleware.js';
import CustomError from './errors/custom.error.js';

// Read env variables
readConfiguration();

// Create the express app
const app = express();
app.disable('x-powered-by');

// Define configurations
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// Define routes
app.use('/event', EventRoutes);
app.use('*', () => {
throw new CustomError(404, 'Path not found.');
});

// Global error handler
app.use(errorMiddleware);

export default app;
25 changes: 1 addition & 24 deletions application-templates/javascript/event/src/index.js
Original file line number Diff line number Diff line change
@@ -1,34 +1,11 @@
import 'dotenv/config';

import express from 'express';
import bodyParser from 'body-parser';

// Import routes
import EventRoutes from './routes/event.route.js';
import { logger } from './utils/logger.utils.js';

import { readConfiguration } from './utils/config.utils.js';
import { errorMiddleware } from './middleware/error.middleware.js';

// Read env variables
readConfiguration();
import app from './app.js';

const PORT = 8080;

// Create the express app
const app = express();
app.disable('x-powered-by');

// Define configurations
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// Define routes
app.use('/event', EventRoutes);

// Global error handler
app.use(errorMiddleware);

// Listen the application
const server = app.listen(PORT, () => {
logger.info(`⚡️ Event application listening on port ${PORT}`);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import CustomError from '../errors/custom.error.js';

export const errorMiddleware = (error, _req, res) => {
export const errorMiddleware = (error, _req, res, _next) => {
const isDevelopment = process.env.NODE_ENV === 'development';

if (error instanceof CustomError) {
Expand All @@ -13,5 +13,11 @@ export const errorMiddleware = (error, _req, res) => {
return;
}

res.status(500).send(isDevelopment ? error : 'Internal server error');
res
.status(500)
.send(
isDevelopment
? { messge: error.message }
: { message: 'Internal server error' }
);
};
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ import { post } from '../controllers/event.controller.js';

const eventRouter = Router();

eventRouter.post('/', (req, res, next) => {
eventRouter.post('/', async (req, res, next) => {
logger.info('Event message received');

try {
post(req, res);
await post(req, res);
} catch (error) {
next(error);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,51 @@
import { expect } from '@jest/globals';
import request from 'supertest';
import app from '../../src/app';
import * as eventController from '../../src/controllers/event.controller';

//@todo: test this with msw (see typescipt job)
// make msw a shared package
describe('Testing Event Controller', () => {
test('POST `/event` route', async () => {
expect(1).toBe(1);
describe('Testing router', () => {
test('Post to non existing route', async () => {
const response = await request(app).post('/none');
expect(response.status).toBe(404);
expect(response.body).toEqual({
message: 'Path not found.',
});
});
test('Post invalid body', async () => {
const response = await request(app).post('/event').send({
message: 'hello world',
});
expect(response.status).toBe(400);
expect(response.body).toEqual({
message: 'Bad request: No customer id in the Pub/Sub message',
});
});
test('Post empty body', async () => {
const response = await request(app).post('/event');
expect(response.status).toBe(400);
expect(response.body).toEqual({
message: 'Bad request: Wrong No Pub/Sub message format',
});
});
});
describe('unexpected error', () => {
let postMock;

beforeEach(() => {
// Mock the post method to throw an error
postMock = jest.spyOn(eventController, 'post').mockImplementation(() => {
throw new Error('Test error');
});
});

afterEach(() => {
// Restore the original implementation
postMock.mockRestore();
});
test('should handle errors thrown by post method', async () => {
// Call the route handler
const response = await request(app).post('/event');
expect(response.status).toBe(500);
expect(response.body).toEqual({ message: 'Internal server error' });
});
});
29 changes: 29 additions & 0 deletions application-templates/javascript/job/src/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import * as dotenv from 'dotenv';
dotenv.config();

import express from 'express';

// Import routes
import JobRoutes from './routes/job.route.js';

import { readConfiguration } from './utils/config.utils.js';
import { errorMiddleware } from './middleware/error.middleware.js';
import CustomError from './errors/custom.error.js';

// Read env variables
readConfiguration();

// Create the express app
const app = express();
app.disable('x-powered-by');

// Define routes
app.use('/job', JobRoutes);
app.use('*', () => {
throw new CustomError(404, 'Path not found.');
});

// Global error handler
app.use(errorMiddleware);

export default app;
22 changes: 1 addition & 21 deletions application-templates/javascript/job/src/index.js
Original file line number Diff line number Diff line change
@@ -1,32 +1,12 @@
import * as dotenv from 'dotenv';
dotenv.config();

import express from 'express';

// Import routes
import JobRoutes from './routes/job.route.js';

// Import logger
import { logger } from './utils/logger.utils.js';

import { readConfiguration } from './utils/config.utils.js';
import { errorMiddleware } from './middleware/error.middleware.js';

// Read env variables
readConfiguration();
import app from './app.js';

const PORT = 8080;

// Create the express app
const app = express();
app.disable('x-powered-by');

// Define routes
app.use('/job', JobRoutes);

// Global error handler
app.use(errorMiddleware);

// Listen the application
const server = app.listen(PORT, () => {
logger.info(`⚡️ Job application listening on port ${PORT}`);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import CustomError from '../errors/custom.error.js';

export const errorMiddleware = (error, _req, res) => {
export const errorMiddleware = (error, _req, res, _next) => {
const isDevelopment = process.env.NODE_ENV === 'development';

if (error instanceof CustomError) {
Expand All @@ -13,5 +13,11 @@ export const errorMiddleware = (error, _req, res) => {
return;
}

res.status(500).send(isDevelopment ? error : 'Internal server error');
res
.status(500)
.send(
isDevelopment
? { messge: error.message }
: { message: 'Internal server error' }
);
};
4 changes: 2 additions & 2 deletions application-templates/javascript/job/src/routes/job.route.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ import { post } from '../controllers/job.controller.js';
// Create the router for our app
const jobRouter = Router();

jobRouter.post('/', (req, res, next) => {
jobRouter.post('/', async (req, res, next) => {
try {
post(req, res);
await post(req, res);
} catch (error) {
next(error);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,35 @@
import { expect } from '@jest/globals';
import request from 'supertest';
import app from '../../src/app';
import * as jobController from '../../src/controllers/job.controller';

describe('Testing Job Template', () => {
test('GET all orders', async () => {
expect(1).toBe(1);
describe('Testing router', () => {
test('Post to non existing route', async () => {
const response = await request(app).post('/none');
expect(response.status).toBe(404);
expect(response.body).toEqual({
message: 'Path not found.',
});
});
});
describe('unexpected error', () => {
let postMock;

beforeEach(() => {
// Mock the post method to throw an error
postMock = jest.spyOn(jobController, 'post').mockImplementation(() => {
throw new Error('Test error');
});
});

afterEach(() => {
// Restore the original implementation
postMock.mockRestore();
});
test('should handle errors thrown by post method', async () => {
// Call the route handler
const response = await request(app).post('/job');
expect(response.status).toBe(500);
expect(response.body).toEqual({ message: 'Internal server error' });
});
});
32 changes: 32 additions & 0 deletions application-templates/javascript/service/src/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import 'dotenv/config';
import express from 'express';
import bodyParser from 'body-parser';

// Import routes
import ServiceRoutes from './routes/service.route.js';

import { readConfiguration } from './utils/config.utils.js';
import { errorMiddleware } from './middleware/error.middleware.js';
import CustomError from './errors/custom.error.js';

// Read env variables
readConfiguration();

// Create the express app
const app = express();
app.disable('x-powered-by');

// Define configurations
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// Define routes
app.use('/service', ServiceRoutes);
app.use('*', () => {
throw new CustomError(404, 'Path not found.');
});

// Global error handler
app.use(errorMiddleware);

export default app;
27 changes: 1 addition & 26 deletions application-templates/javascript/service/src/index.js
Original file line number Diff line number Diff line change
@@ -1,35 +1,10 @@
import 'dotenv/config';
import express from 'express';
import bodyParser from 'body-parser';

// Import routes
import ServiceRoutes from './routes/service.route.js';

// Import logger
import { logger } from './utils/logger.utils.js';

import { readConfiguration } from './utils/config.utils.js';
import { errorMiddleware } from './middleware/error.middleware.js';

// Read env variables
readConfiguration();
import app from './app';

const PORT = 8080;

// Create the express app
const app = express();
app.disable('x-powered-by');

// Define configurations
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// Define routes
app.use('/service', ServiceRoutes);

// Global error handler
app.use(errorMiddleware);

// Listen the application
const server = app.listen(PORT, () => {
logger.info(`⚡️ Service application listening on port ${PORT}`);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import CustomError from '../errors/custom.error.js';

export const errorMiddleware = (error, _req, res) => {
export const errorMiddleware = (error, _req, res, _next) => {
const isDevelopment = process.env.NODE_ENV === 'development';

if (error instanceof CustomError) {
Expand All @@ -12,6 +12,11 @@ export const errorMiddleware = (error, _req, res) => {

return;
}

res.status(500).send(isDevelopment ? error : 'Internal server error');
res
.status(500)
.send(
isDevelopment
? { messge: error.message }
: { message: 'Internal server error' }
);
};
Loading

0 comments on commit a532cdd

Please sign in to comment.