简体   繁体   English

用Jest和Mongoose进行Express API测试

[英]Express API Test with Jest and Mongoose

I am working on an API server in express with using mongoose to connect to a MongoDB. 我正在使用mongoose连接到MongoDB来快速地在API服务器上工作。

node kicks off index.js which starts an app.js where I do the MongoDB setup and the express setup. 节点启动index.js,这将启动一个app.js,在其中执行MongoDB安装和快速安装。

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测试API时,猫鼬在测试完成后完成了连接的问题,因此jest给了我以下错误。

Jest did not exit one second after the test run has completed. 测试运行一秒钟后,Jest没有退出。

This usually means that there are asynchronous operations that weren't stopped in your tests. 这通常意味着您的测试中没有停止异步操作。 Consider running Jest with --detectOpenHandles to troubleshoot this issue. 考虑使用--detectOpenHandles运行Jest来解决此问题。

I know logically it is due to node.js's async nature. 从逻辑上我知道这是由于node.js的异步特性引起的。 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更改了连接字符串以供公开发布。

app.js 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. 发生的一切是系统正在桥接MongoDB,它没有在测试中对其进行任何事务。 (As the other question talks about). (正如另一个问题所讨论的)。

Finally in that example they are trying to bring up the mongoose db in the test itself. 最后,在该示例中,他们尝试在测试本身中启动mongoose db。 I'm brining it up as part of the app startup (as it works when I run the routes in dev). 我将其作为应用程序启动的一部分进行桥接(因为当我在dev中运行路由时,它可以正常工作)。

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

In package.json you can re-write the test script. 在package.json中,您可以重新编写测试脚本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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