Mocha-Express 单元测试失败,本地主机为 URL

Mocha-Express unit test fails with localhost as URL

我写了下面的脚本(server.js):

var express = require('express'),
    app = express(),
    server;

app.get('/', function (request, response) {
  response.send('This is the main page.\n');});

exports.listen = function (port){
    server = app.listen(port, function () {
    console.log('Server available listening at: ' + port);}) };

exports.close = function () {
  server.close(function (){
    console.log('Server Closed')}); };

以及以下 Mocha 单元测试 (test.js):

var server = require ('./server'),
    assert = require ('assert'),
    http = require ('http');
var port = 8085;

describe('server', function () {
  before(function () {
    server.listen(port)});

  after(function () {
    server.close();}); });

describe('Server status and Message', function () {
  it('status response should be equal 200', function (done) {
    http.get('http://127.0.0.1:8085', function (response) {
         assert.equal(response.statusCode, 200);
        done(); }); }); }); 

当我 运行 test.js 将 'localhost:8085' 或 '127.0.0.1:8085' 传递给 http 客户端时,无论使用何种端口,Mocha 都会显示以下错误:

1) Server status and Message status response should be equal 200:
     Uncaught Error: connect ECONNREFUSED
      at exports._errnoException (util.js:746:11)
      at TCPConnectWrap.afterConnect [as oncomplete] (net.js:983:19)

但我可以通过具有相同本地主机的 http 客户端完美连接服务器 url (listener.js):

var server = require('./server');
var http = require('http');

    var url = 'http://localhost:8085';
    var content = function(response){
        response.setEncoding("utf8");       
        response.on("data", function(data) {
                console.log(data)});}

    server.listen(8085);
    setTimeout(function (){server.close();}, 3000)

    http.get(url, content);

我已经尝试 运行与其他互联网 url 进行单元测试作为“https://www.google.com.co/”(测试未通过但有效)和测试 运行正确。

你能帮我解决这个问题吗?非常感谢。

您不小心 运行 进行了两组测试。将第二个 describe() 移到第一个中,这样它就可以依赖 before() 挂钩,如下所示:

var server = require ('./server'),
    assert = require ('assert'),
    http = require ('http');
var port = 8085;

describe('server', function () {
    before(function () {
        server.listen(port);
    });

    after(function () {
        server.close();
    });

    describe('Server status and Message', function () {
      it('status response should be equal 200', function (done) {
            http.get('http://127.0.0.1:8085', function (response) {
                  assert.equal(response.statusCode, 200);
                  done();
            });
       });
    });
});