node.js 中的 Mocha 测试挂起或丢失

Mocha tests in node.js hanging or missing

目前我正在做一个项目,我应该在 node.js 中使用 express.js 编写路由。

项目的测试和其他部分不是我写的,因此我认为它们没有错误。

我遇到的问题是:在程序的当前阶段,当我 运行“npm test”时,我的测试挂起并且控制无法返回到命令行。我注意到当我注释掉 server.js、api.js 和 employees.js 中的所有行时,测试 运行 顺利进行。

此外,有时只执行一部分测试,比如其中的 1/3。

知道为什么测试挂起,以及如何修复它们吗?

这里是 package.json 文件加上目前项目的主要文件。

提前致谢。

package.json

{
  "name": "expresso",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "test": "mocha"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.19.0",
    "chai": "^4.1.2",
    "cors": "^2.8.5",
    "errorhandler": "^1.5.1",
    "express": "^4.17.1",
    "mocha": "^6.1.4",
    "react": "^15.6.1",
    "react-dom": "^15.6.1",
    "react-router-dom": "^4.2.2",
    "sqlite3": "^4.0.6",
    "supertest": "^3.0.0",
    "whatwg-fetch": "^2.0.3"
  },
  "devDependencies": {
    "babel": "^6.23.0",
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "babel-preset-stage-2": "^6.24.1",
    "webpack": "^3.5.5"
  }
}

server.js

const bodyParser = require('body-parser');
const cors = require('cors');
const errorHandler = require('errorhandler');
const express = require('express');
const apiRouter = require('./api/api');

const app = express();
const PORT = process.env.PORT || 4000;

app.use(bodyParser.json());
app.use(cors());

app.use('/api', apiRouter);

app.use(errorHandler());

app.listen(PORT, () => {
    console.log(`Listening on port ${PORT}`);
});

module.exports = app;

api.js

const express = require('express');
const apiRouter = express.Router();
const employeesRouter = require('./employees');

    // <<< api/employees >>>
apiRouter.use('/employees', employeesRouter);

module.exports = apiRouter;

employees.js

const express = require('express');
const employeesRouter = express.Router();

const sqlite = require('sqlite3');
const db = new sqlite.Database('./database.sqlite');

    // <<< api/employees >>>
employeesRouter.get('/', (req, res, next) => {
    const sql = 'SELECT * FROM Employee WHERE is_current_employee = 1';

    db.all(sql, (error, employees) => {
        if (error) {
            next(error);
        } else {
            res.status(200).json({ employees: employees });
        }
    });

});


module.exports = employeesRouter;

您必须将 scripts -> test 中的标签 --exit 添加到您的 package.json

结果应该是这样的:

"scripts": {
  "test": "mocha --exit"
}

根据docs

--exit : Force Mocha to quit after tests complete

之后,当测试完成时,命令行再次可用。