How to run Koa server before Tests in Mocha? - node.js

I read a lot of answers to similar questions already but can't figure out what is wrong in my code.
this is my server.js file
const Koa = require('koa')
const Router = require('koa-router')
const app = new Koa()
app.use(require('koa-bodyparser')())
const login = (ctx, next) => {
ctx.body = ctx.request.body
}
const router = new Router({ prefix: '/api' })
router.get('/test', (ctx, next) => {
ctx.body = { resp: 'GET REQUEST /test WORKING' }
})
router.post('/login', login)
app.use(router.routes())
module.exports = app
this is my index.js file
const server = require('./server')
server.listen(3000, () => {
console.log('App is running on http://localhost:3000')
})
and this is my mocha test file
const axios = require('axios').default
const expect = require('chai').expect
const app = require('./server')
describe('7-module-3-task', () => {
describe('test', function () {
let server
before(done => {
server = app.listen(3000, done)
})
after(async () => {
server.close()
})
it('should return response from server', async () => {
const response = await axios.get('http://localhost:3000/api/test')
expect(response.data, 'should return object with key "resp').to.have.property('resp')
})
})
})
It's working okay when I make a request in Postman. I tried multiple options already but I still get 404 response, as I understand test is performed before server started running...? How can I make it working ?

First, I would move the startup (app.listen) directly into the server.js (not critical, but maybe more simpler because the require in your test would then already start your server:
const Koa = require('koa')
const Router = require('koa-router')
const app = new Koa()
app.use(require('koa-bodyparser')())
const router = new Router({ prefix: '/api' })
router.get('/test', (ctx, next) => {
ctx.body = { resp: 'GET REQUEST /test WORKING' }
})
app.use(router.routes())
app.listen(3000); // can be a parameter but for simplicity hardcoded here
module.exports = app
In your test you then do:
let chai = require('chai');
let chaiHttp = require('chai-http');
let server = require('./server'); // this will already start up your server
describe('API Tests', () => {
describe('TEST endpoint', () => {
it('It should GET response from test endpoint', (done) => {
chai.request('http://localhost:3000')
.get('/api/test/') // be sure to have a trailing '/' !!
.end((err, res) => {
res.body.should.have.property('resp');
done();
});
})
});
});
One more hint: maybe in your original code you just have to make sure, that you have a trailing / when calling your route in the test.
Code snippets not testet but I hope you get the idea.

I shared the same code with 2 of my friends and they managed to run tests successfully.
I tested it on my other laptop after this and tests worked as well.
The problem was in the port. 3000 port was used as a default one in the debugger in Webstorm, not sure why but still.
Launching the server on port 3000 in a regular way, not in mocha tests, worked very well but in tests, it did not work, not sure why.
So for those who ever face something similar, check the default port of the debugger or any other built-in server.

Related

Ensure express app is running before starting mocha tests

I built an API for a couchbase database, using express and node.js. My problem is that when I run my tests some of them fail, because the server is not fully running. I found a solution here https://mrvautin.com/ensure-express-app-started-before-tests on how to solve this issue. The article stated that in order to solve this issue, you have to add an event emitter in your server file like this
app.listen(app_port, app_host, function () {
console.log('App has started');
app.emit("appStarted");
});
and then add this, in your test file
before(function (done) {
app.on("appStarted", function(){
done();
});
});
I have tried this, here is my implementation
Server File
app.listen(config['server']['port'], function(){
app.emit("appStarted");
logger.info("Listening")
})
Test File
before(function(done){
app.on("appStarted", function(){
done();
})
});
I keep on getting the following error
1) "before all" hook in "{root}":
Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.
at listOnTimeout (internal/timers.js:549:17)
at processTimers (internal/timers.js:492:7)
The article is from 2016, so I was thinking that maybe the syntax has been deprecated. I was wondering if someone could please help point me in the right direction?
You can add the below condition, more info see "Accessing the main module".
if (require.main === module) {
// this module was run directly from the command line as in node xxx.js
} else {
// this module was not run directly from the command line and probably loaded by something else
}
E.g.
index.ts:
import express from 'express';
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.sendStatus(200);
});
if (require.main === module) {
app.listen(port, () => {
console.log('App has started');
});
}
export { app, port };
index.test.ts:
import { app, port } from './';
import http from 'http';
import request from 'supertest';
describe('63822664', () => {
let server: http.Server;
before((done) => {
server = app.listen(port, () => {
console.log('App has started');
done();
});
});
after((done) => {
server.close(done);
console.log('App has closed');
});
it('should pass', () => {
return request(server)
.get('/')
.expect(200);
});
});
integration test result:
(node:22869) ExperimentalWarning: The fs.promises API is experimental
63822664
App has started
✓ should pass
App has closed
1 passing (26ms)
!Hi World! My little solution here:
Check this: All depends of your testing markup...
For example, I'm using Mocha and Chai Assertion Library.
const express = require('express');
const request = require("request");
const http = require("http");
const expect = require("chai").expect;
require('dotenv').config();
describe('Server', function() {
const { PORT } = process.env;
const app = express();
before((done) => {
http.Server = app.listen(PORT, () => {
console.log(`Listening Node.js server on port: ${PORT}`);
done();
});
});
it('should return 404 response code status', () => {
const url = `http://localhost:${PORT}/api/v1/yourPath`;
return request(url, (err, response, body) => {
/* Note this result 'cause I don't have any get('/')
controller o function to return another code status
*/
expect(response.statusCode).to.equal(404);
});
})
});

Simple node http server unit test

I created a NodeJs http server in TypeScript and I've unit tested everything with Jest, except the base class, the server itself:
import { createServer} from 'http';
export class Server {
public startServer() {
createServer(async (req, res) => {
if(req.url == 'case1') {
// do case1 stuff
}
if(req.url == 'case2') {
// do case2 stuff
}
res.end();
}).listen(8080);
}
}
I'm trying this approach:
import { Server } from '../../../src/app/Server/Server';
import * as http from 'http';
describe('Server test suite', () => {
function fakeCreateServer() {
return {}
}
test('start server', () => {
const serverSpy = jest.spyOn(http, 'createServer').mockImplementation(fakeCreateServer);
const server = new Server().startServer();
expect(serverSpy).toBeCalled();
});
});
Is there a way a can create a valid fake implementation for the 'createServer' method?
And maybe simulate some requests?
Thanks a lot!
What logic do you want to test here?
Such a simple server is declarative enough to keep it without unit tests.
If you want to test that createServer is invoked
just mock http module by jest.mock('http');
Such expressions are lifted up by jest to give them precedence over regular imports.
https://jestjs.io/docs/en/mock-functions#mocking-modules
import { Server } from '../../../src/app/Server/Server';
import * as http from 'http';
jest.mock('http', () => ({
createServer: jest.fn(() => ({ listen: jest.fn() })),
}));
describe('Server', () => {
it('should create server on port 8080', () => {
const server = new Server().startServer();
expect(http.createServer).toBeCalled();
});
});
Maybe you should approach your class and tests a little bit differently.
Nodejs http.createServer returns a server instance. The server instance has a property listening (true if the server is listening for the requests), so you could return the server instance from the startServer method and test server.listening property.
Also, if you want to test for different responses and requests to your server, I would suggest you use supertest
// server.js - it also works with plain HTTP
const app = express();
app.get('/user', function(req, res) {
res.status(200).json({ name: 'john' });
});
module.export = app
// test.js
const request = require('supertest');
const app = require('./server.js')
describe('GET /user', function() {
it('responds with json', function(done) {
request(app)
.get('/user')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200, done);
});
});

JSDOM - nodejs makes clean exit, doesn't load

I am following a tutorial on this site:
https://phasertutorials.com/creating-a-simple-multiplayer-game-in-phaser-3-with-an-authoritative-server-part-1/
I am trying to get the last step to work.
I tried this initially with my own code as I am begining to understand using node and express. I got the same error, so I did a clean start and followed the guide exactly as I thought I had made a mistake and couldn't find it. But now I think there is an issue in this function, I don't know of.
Everything works fine until I reach the last step- including this function:
function setupAuthoritativePhaser() {
JSDOM.fromFile(path.join(__dirname, 'authoritative_server/index.html'), {
// To run the scripts in the html file
runScripts: "dangerously",
// Also load supported external resources
resources: "usable",
// So requestAnimatinFrame events fire
pretendToBeVisual: true
}).then((dom) => {
dom.window.gameLoaded = () => {
server.listen(8081, function () {
console.log(`Listening on ${server.address().port}`);
});
};
}).catch((error) => {
console.log(error.message);
});
};
my nodemon makes a clean exit and waits for changes before restarting.
any ideas?
Your help is greatly appreciated.
I found my own answer. Apparently I am a fool, I removed the call of this function...
setupAuthoritativePhaser();
However, I am not getting the correct phaser tag in the console log, it should say Phaser .... (Headless | HTML5 Audio) but it still says Phaser v3.15.1 (WebGL | Web Audio), though in my node it says the correct phrase...
you need remove old code in server/index.js
server.listen(8081, function () {
console.log(`Listening on ${server.address().port}`);
});
and use
dom.window.gameLoaded = () => {
server.listen(8081, function () {
console.log(`Listening on the ${server.address().port}`);
});
};
finaly server/index.js look like
const express = require('express');
const app = express();
const server = require('http').Server(app);
const path = require('path');
const jsdom = require('jsdom');
const { JSDOM } = jsdom;
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
// server.listen(8081, function () {
// console.log(`Listening on ${server.address().port}`);
// });
function setupAuthoritativePhaser() {
console.log(__dirname)
JSDOM.fromFile(path.join(__dirname, '/authoritative_server/index.html'), {
// To run the scripts in the html file
runScripts: "dangerously",
// Also load supported external resources
resources: "usable",
// So requestAnimatinFrame events fire
pretendToBeVisual: true
}).then((dom) => {
dom.window.gameLoaded = () => {
server.listen(8081, function () {
console.log(`Listening on the ${server.address().port}`);
});
};
}).catch((error) => {
console.log(error.message);
});
}
setupAuthoritativePhaser();

EADDRINUSE :::3000 in jest

I know this error means that port 3000 is already in use but I also tried a different port but I am still getting the same errors for some specific tests only.
This is the code of one of those test
describe("GET /", () => {
it("should return all genres", async() => {
await Genre.collection.insertMany([
{name: 'genre1'},
{name: 'genre2'}
]);
const res = await request(server).get('/api/genres');
expect(res.status).toBe(200);
expect(res.body.length).toBe(2);
expect(res.body.some( g => g.name === 'genre1')).toBeTruthy();
expect(res.body.some( g => g.name === 'genre2')).toBeTruthy();
});
});
Any way to solve this error?
listen EADDRINUSE :::3000
10 |
11 | const port = process.env.PORT || 3000;
> 12 | const server = app.listen(port, () => winston.info(`Listening on port ${port}...`));
| ^
13 |
14 | module.exports = server;
15 |
at Function.listen (node_modules/express/lib/application.js:618:24)
at Object.listen (index.js:12:20)
● /api/returns › Should return 400 if customerId is not given
connect ECONNREFUSED 127.0.0.1:62801
This is what i'm getting in the console
I think that the issue is down to not closing the server between test runs in Jest.
If you're using jest --watch to run your tests then it might help to add an afterAll handler?
Example minimal express app:
// app.js
const express = require("express");
const app = express();
// Server port
const HTTP_PORT = 3000;
// Start server
server = app.listen(HTTP_PORT, () => {
//console.log(`Server running on port ${HTTP_PORT}`);
});
// Root endpoint
app.get("/", (req, res, next) => {
res.json({"message":"Ok yah!"})
});
// Default response for any other request
app.use(function(req, res){
res.status(404);
});
module.exports = server;
Test file:
// app.test.js
const app = require('../app');
describe('GET /', () => {
let response;
it('proves Jest works', () => {
expect(1).toBe(1);
});
it('proves maths still works', () => {
expect(1+1).toBe(2);
});
});
// remembering to CLOSE the server after tests completed.
afterAll(async () => {
await app.close();
});

Mocha testing socketio middleware won't finish suite

I am testing an nodejs-app with a server and a client component on nodejs 8.9 with mocha.
For mocha to end properly, I have to make sure that all socketio and http-servers are closed after the tests have been run. This works fine with normal tests, but as soon as I register a middleware to the socketio-server, the mocha-process won't close and stay open forever.
Testcode (comment in the second test to see the problem, run via mocha test.spec.js):
// test.spec.js
'use strict'
const Express = require('express')
const Http = require('http')
const ioserver = require('socket.io')
const ioclient = require('socket.io-client')
const NODE_PORT = process.env.NODE_PORT || 3000
describe('Client', function () {
beforeEach(() => {
const express = new Express()
this._http = Http.Server(express)
this._ioserver = ioserver(this._http)
this._http.listen(NODE_PORT)
})
// this test works perfectly, even when I copy it and run it
// multiple times in this suite
it('should connect to a socketio-server', (done) => {
this._ioserver.on('connection', () => {
client.close()
done()
})
const client = ioclient.connect(`http://localhost:${NODE_PORT}`)
})
// this test also finished, but the suite hangs afterwards - as if
// a socket-client or socket-server was not closed properly.
it('should finish the test suite even with a middleware', (done) => {
this._ioserver.use((socket, next) => {
return next()
})
this._ioserver.on('connection', () => {
client.close()
done()
})
const client = ioclient.connect(`http://localhost:${NODE_PORT}`)
})
afterEach(() => {
this._ioserver.close()
this._http.close()
})
})
Any ideas why that happens?
So, the problem was, that the server closed the client connection on a successful connection event. The client did not get any information on that, but instead saw a failed connection and tried to reconnect. This opened a socket to the server again and because the server was already closed, the connection error kept coming.
This behavior stopped node from properly destroying all objects, which in turn explaines the hanging. The solution is to call done() only after the client has declared a connection open, not after the server has declared a connection open like so:
'use strict'
const Express = require('express')
const Http = require('http')
const ioserver = require('socket.io')
const ioclient = require('socket.io-client')
const NODE_PORT = process.env.NODE_PORT || 3000
describe('Client', function () {
beforeEach(() => {
const express = new Express()
this._http = Http.Server(express)
this._ioserver = ioserver(this._http)
this._http.listen(NODE_PORT)
this._client = null
})
it('should connect to a socketio-server', (done) => {
this._ioserver.on('connection', () => {
done()
})
this._client = ioclient.connect(`http://localhost:${NODE_PORT}`)
})
it('should finish the test suite even with a middleware', (done) => {
this._ioserver.use((socket, next) => {
return next()
})
this._client = ioclient.connect(`http://localhost:${NODE_PORT}`)
// if we wait for the server and kill the server socket,
// the client will try to reconnect and won't be killed
// by mocha.
this._client.on('connect', () => {
done()
})
})
afterEach(() => {
// this last call forces the client to stop connecting
// even if tests failed
this._client.close()
this._ioserver.close()
this._http.close()
})
})

Resources