简体   繁体   中英

Express API Test with Jest and Mongoose

I am working on an API server in express with using mongoose to connect to a MongoDB.

node kicks off index.js which starts an app.js where I do the MongoDB setup and the express setup.

Works fine in normal development, but when I try to use jest to test the APIs I have issues with the mongoose finishing it's connection after the test is complete, and thus jest gives me the following error.

Jest did not exit one second after the test run has completed.

This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with --detectOpenHandles to troubleshoot this issue.

I know logically it is due to node.js's async nature. I just don't know how to fix it. I don't know if the solution is restructuring the way I'm running the calls or doing something with promises (which I'm still really weak on).

So how can I fix this issue? App.js posted below with the connect string altered for public posting.

app.js

import express from 'express';
import path from 'path';
import logger from 'morgan';
import bodyParser from 'body-parser';
import cors from 'cors';
import mongoose from 'mongoose';
import fs from 'fs';

//Bring DB Online
console.log("Brining MongoDB Online")
mongoose.set('debug', true)

const devurl = 'mongodb://mlabuname:mlabpass@ds247170.mlab.com:47170/devdb'
mongoose.connect(devurl, { useNewUrlParser:true }, function() {
  console.log('\tMongoDB - Connection has been made');
})
.catch(err => {
    console.error('\tApp starting error:', err.stack);


  process.exit(1);
});

//Load Models
console.log("\tLoading Mongoose Models")
import User from './models/user'
import Wiki from './models/wiki'

//Express Items
console.log("Brining Express Online")
const app = express();
app.disable('x-powered-by');
app.use(cors());

// View engine setup
app.set('views', path.join(__dirname, '../views'));
app.set('view engine', 'pug');

app.use(logger('dev', {
  skip: () => app.get('env') === 'test'
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, '../public')));

// Routes
// Dynamic routes setup by controllers
console.log("\tInstalling Controller Routes")
fs.readdirSync("src/controllers").forEach(function (file) {
  if(file.substr(-3) == ".js") {
    const route = require("./controllers/" + file)
    route.controller(app)
  }
})

// Temp ResetDB Route for DEV.
console.log("\tInstalling ResetDB Route")
import resetDB from './routes/resetDB'
app.use('/resetDB', resetDB);

// Default Routes set by the framework, fine for now.
console.log("\tInstalling Default")
import defaultRoutes from './routes/defaultRoutes'
app.use('/', defaultRoutes);

// Catch 404 and forward to error handler
app.use((req, res, next) => {
  const err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// Error handler
app.use((err, req, res, next) => { // eslint-disable-line no-unused-vars
  res
    .status(err.status || 500)
    .render('error', {
      message: err.message
    });
});

export default app;

Update I have been pointed to this being a duplicate. I saw that answer and it isn't exactly the same issue. First they are actually testing the model. In this case I am not. I'm simply trying to run the test on the express routes, and the error is showing up after the test ran (and passed).

All that is happening is the system is brining up the MongoDB it isn't doing any transactions to it as part of the test. (As the other question talks about).

Finally in that example they are trying to bring up the mongoose db in the test itself. I'm brining it up as part of the app startup (as it works when I run the routes in dev).

 "scripts": {
        "test": "jest  --watchAll --detectOpenHandles --forceExit"
      }

In package.json you can re-write the test script.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM