【发布时间】:2017-06-08 05:30:55
【问题描述】:
我正在关注Mocha test docs 对某些 API 路由进行单元测试。
为此,我设置了一个包含 index.test.js 的\test 目录。测试文件所需的已安装包,包括mocha。然后在package.json中指定了运行mocha的命令,npm test:
"scripts": {
"test": "mocha ./test",
"start": "node index.js"
},
但是当我从包含 index.test.js 的测试目录中运行 npm test 时。测试似乎没有运行,只是显示给我:
我也参考了这个 Stackoverfow 答案,但无济于事 - Configure node npm package.json so that "npm test" works on both unix and windows
问题:
如何从 npm 脚本运行 mocha 测试文件?
这是测试文件的目录位置-C:\Users\brianj\Documents\Projects\WebService-for-Self-service-Metrics-Portal\test\index.test.js
这是来自\test 的名为 index.test.js 的实际测试文件,在调用 mocha 之前已经安装了所需的包:
var chai = require('chai');
var should = chai.should();
var sinon = require('sinon');
var request = require('supertest');
var _ = require('lodash');
var express = require('express');
var app = express();
// Global array to store all relevant args of calls to app.use
var APP_USED = []
// Replace the `use` function to store the routers and the urls they operate on
app.use = function() {
var urlBase = arguments[0];
// Find the router in the args list
_.forEach(arguments, function(arg) {
if (arg.name == 'router') {
APP_USED.push({
urlBase: urlBase,
router: arg
});
}
});
};
// GRAB all the routes from our saved routers:
_.each(APP_USED, function(used) {
// On each route of the router
_.each(used.router.stack, function(stackElement) {
if (stackElement.route) {
var path = stackElement.route.path;
var method = stackElement.route.stack[0].method.toUpperCase();
console.log(method + " -> " + used.urlBase + path);
describe(method + " -> " + used.urlBase + path, function() {
request(app)
.get(used.urlBase + path)
.expect('Content-Type', /json/)
.expect(200, "ok")
.end(function(err, res){
if (err) throw err;
});
}); //
}
});
});
【问题讨论】:
-
动态测试路由器的目的是什么?只需编写您需要的临时测试。我永远不会以这种方式编写测试,因为您可以看到您也需要测试测试;P
-
我可能弄错了,但似乎在执行脚本后 APP_USED 保持为空,因为您没有在任何地方调用 app.user 。所以第一个 _.each 没有迭代。
标签: node.js express automated-tests mocha.js