这是我的集群 Express 应用程序的简化版本:
/index.js
module.exports = process.env.CODE_COV
? require('./lib-cov/app')
: require('./lib/app');
/lib/app.js
var cluster = require('cluster'),
express = require('express'),
app = module.exports = express.createServer();
if (cluster.isMaster) {
// Considering I have 4 cores.
for (var i = 0; i < 4; ++i) {
cluster.fork();
}
} else {
// do app configurations, then...
// Don't listen to this port if the app is required from a test script.
if (!module.parent.parent) {
app.listen(8080);
}
}
/test/test1.js
var app = require('../');
app.listen(7777);
// send requests to app, then assert the response.
问题:
var app = require('../');
在此集群环境中不起作用。它应该返回哪个工作应用程序?它应该返回集群对象而不是 Express 应用吗?- 现在,显然在测试脚本中设置端口是行不通的。您将如何在测试脚本中为应用集群设置一个端口?
- 您将如何向这组应用发送请求?
我能想到的唯一解决方案是有条件地关闭集群功能并仅运行一个应用程序,如果该应用程序是从测试脚本请求的(if (module.parent.parent) ...
).
还有其他方法可以使用 Mocha 测试集群 Express 应用吗?
最佳答案
很久没发这个问题了。由于没有人回答,我将自己回答这个问题。
我保留了 /index.js 原样:
module.exports = process.env.CODE_COV
? require('./lib-cov/app')
: require('./lib/app');
在启动集群的/lib/app.js 中,我有以下代码。简而言之,我只在非测试环境中启动集群。在测试环境中,集群未启动,但只有一个应用程序/工作程序本身按照 cluster.isMaster && !module.parent.parent
条件中的定义启动。
var cluster = require('cluster'),
express = require('express'),
app = module.exports = express.createServer();
if (cluster.isMaster && !module.parent.parent) {
// Considering I have 4 cores.
for (var i = 0; i < 4; ++i) {
cluster.fork();
}
} else {
// do app configurations, then...
// Don't listen to this port if the app is required from a test script.
if (!module.parent.parent) {
app.listen(8080);
}
}
在上述情况下,只有当应用程序不是由测试脚本启动时,!module.parent.parent
才会被评估为真实对象。
module
是当前的 /lib/app.js 脚本。module.parent
是它的父 /index.js 脚本。module.parent.parent
是undefined
如果应用程序是直接通过node index.js
启动的。module.parent.parent
是测试脚本(如果应用程序是通过其中一个脚本启动的)。
因此,我可以安全地启动可以设置自定义端口的脚本。
/test/test1.js
var app = require('../');
app.listen(7777);
// send requests to app, then assert the response.
同时,如果我需要真正运行应用程序,即不是为了测试,那么我运行 node index.js
它将启动应用程序集群。
关于node.js - 如何使用 Mocha 测试集群 Express 应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17737448/