node.js - 如何使用 Mocha 测试集群 Express 应用程序?

标签 node.js express

这是我的集群 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.

问题:

  1. var app = require('../'); 在此集群环境中不起作用。它应该返回哪个工作应用程序?它应该返回集群对象而不是 Express 应用吗?
  2. 现在,显然在测试脚本中设置端口是行不通的。您将如何在测试脚本中为应用集群设置一个端口?
  3. 您将如何向这组应用发送请求?

我能想到的唯一解决方案是有条件地关闭集群功能并仅运行一个应用程序,如果该应用程序是从测试脚本请求的(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 才会被评估为真实对象。

  1. module 是当前的 /lib/app.js 脚本。
  2. module.parent 是它的父 /index.js 脚本。
  3. module.parent.parentundefined 如果应用程序是直接通过 node index.js 启动的。
  4. 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/

相关文章:

node.js - 在用户注销后,如何防止浏览器的后退按钮访问受限信息?

node.js - Knex.js 多链式查询

node.js - Nodejs Express 应用程序,传播错误

javascript - 链接在使用 node.js 和 ejs 的多页网站中不起作用

node.js - ionic 应用程序在链接包中找不到提供者

javascript - 如何在sequelize.js、node中以关联模式插入数据

node.js - 如何从 ionic 公开静态 html 页面

node.js - 客户端连接到 Node js TCP 服务器后立即断开连接

node.js - Express 3.4.8 图片上传问题 - 不使用bodyParser()如何解决?

node.js - 环回引用许多嵌套外键