Categories
express jestjs node.js

Jest tests hanging even after running server.close() on my express app

I have an express app which I need to start on my integration test case.

The express app is exported in the app.js file without listening to any port. So, my test case goes like this:

const app = require('../src/app');
describe('Pact Verification', () => {
const port = 3002;
let server;
beforeAll(done => {
const server = http.createServer(app);
server.listen({ port }, done)
});
afterAll(done => {
server.close(done);
});
it(....

The problem is, once the test is ran with Jest, it hangs. I have to either --forceExit or ^C to exit.

I even updated to Jest 23 to use –detectOpenHandles but I don’t see any output in the terminal, it keeps hanging so that’s not helping either.

Since the exported app is not listening to any port, and it doesn’t have any database connections or such, the problem is unlikely to be there, maybe its in my beforeAll/afterAll block. What am I missing?

Update 1

Here is the content of my app.js

var express = require('express');
var path = require('path');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var app = express();
if (process.env.NODE_ENV !== 'test') {
app.use(logger('dev'));
}
app.use(express.json());
app.use('/api/v1/', indexRouter); // <-- these endpoints just return faker data in JSON format (https://github.com/marak/Faker.js/)
app.use((req, res, next) => {
const err = Error('Not Found');
err.status = 404;
next(err);
});
app.use((err, req, res, next) => {
const { status, message } = err;
const stack = status !== 404 && err.stack || undefined;
res.status(status || 500)
.json({
message,
stack,
});
});
module.exports = app;