Skip to content

Commit

Permalink
Add callback function to server start
Browse files Browse the repository at this point in the history
  • Loading branch information
knor-el-snor committed Mar 16, 2018
1 parent 38064fd commit 34bdfe7
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
5 changes: 4 additions & 1 deletion src/lib/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import * as fs from 'fs';
/**
* Start an http/https server from the given Express instance
*/
export function startServer(app: Application, options: ServerOptions): void {
export function startServer(app: Application, options: ServerOptions, callbackFn?: Function): void {
const httpServer = http.createServer(app);
httpServer.listen(options.port);
console.log(`${options.title || 'TreeHouse'} HTTP NodeJS Server listening on port ${options.port}`);
Expand All @@ -18,6 +18,9 @@ export function startServer(app: Application, options: ServerOptions): void {
httpsServer.listen(options.https.port);
console.log(`${options.title || 'TreeHouse'} HTTPS NodeJS Server listening on port ${options.https.port}`);
}

// Optional callback function
if (callbackFn) callbackFn();
}


Expand Down
15 changes: 13 additions & 2 deletions tests/server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,27 @@ const CONFIGURATION = {
describe('Initialise things before running application', () => {
describe('#startServer', () => {
let app;

beforeEach(() => {
app = express();
});
test('start http server', async () => {

test('should start http server', async () => {
startServer(app, CONFIGURATION);

app.use('/', (req, res) => res.json('welcome'));
const response = await request(app).get('/');
expect(response.status).toEqual(200);
});
test('start http server should throw error on invalid https configuration', async () => {


test('should start http server with provided callbackFn', async () => {
const mockFn = jest.fn();
startServer(app, { port: 5003 }, mockFn);
expect(mockFn).toHaveBeenCalledTimes(1);
});

test('should start http server should throw error on invalid https configuration', async () => {
const WRONG_CONFIGURATION = Object.assign({}, CONFIGURATION, {
title: 'Tree House',
port: 5000,
Expand All @@ -35,6 +45,7 @@ describe('Initialise things before running application', () => {
},
});
expect.assertions(2);

try {
startServer(app, WRONG_CONFIGURATION);
} catch (err) {
Expand Down

0 comments on commit 34bdfe7

Please sign in to comment.