运行茉莉花规格后关闭Express服务器 [英] Closing an express server after running jasmine specs

查看:108
本文介绍了运行茉莉花规格后关闭Express服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对我的快速服务器进行茉莉花测试.我正在为每个规格旋转一个新服务器,并在每个规格完成后尝试将其关闭.不幸的是,服务器似乎并没有关闭...使得无法运行多个规格.

I am trying to set up jasmine testing of my express server. I am spinning up a new server with each spec and trying to shut it down after each spec completes. Unfortunately, the server doesn't seem to be shutting down... making running more than one spec impossible.

server.js:

server.js:

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

exports.start = function(config){
  if(!this.server){
    app.get('/', function(req, res){
      res.status(200);
      res.end();
    })

    this.server = app.listen(config.port, function(){
      console.log('Server running on port %d', config.port);
    });
  }
};

exports.close = function(){
  this.server.close();
}

routing-spec.js:

routing-spec.js:

var server = require('./path/to/server.js');
var http = require('http');

describe('express server', function () {
  beforeEach(function () {
    server.start({port: 8000});
  });

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

  describe('/', function () {
    it('should return 200', function (done) {
      http.get('http://localhost:8000', function (res) {
        expect(res.statusCode).toBe(200);
        done();
      });
    });
  });
});

第一个规范通过了预期,但是终端从未完成测试(即:服务器仍在运行),并且随后添加的任何测试都会引发"ECONNREFUSED".

The first spec passes as expected but the terminal never completes the test(ie: the server is still running) and any subsequent tests added cause a "ECONNREFUSED" to be thrown.

推荐答案

您可以使用npm模块服务器销毁.服务器销毁跟踪所有连接,然后在调用destroy时将其关闭.另外,destroy方法接受回调,因此您应将"done"函数传递给destroy方法...下面是从npm模块描述中复制的内容,在destroy调用中添加了回调.

You can use the npm module server-destroy. server-destroy keeps track of all connections and then closes them when destroy is called. Also, the destroy method takes a callback so you should pass your "done" function to your destroy method... Below is copied from the npm module description with the addition of a callback in the destroy call.

var enableDestroy = require('server-destroy');

var server = http.createServer(function(req, res) {
  // do stuff, blah blah blah
});

server.listen(PORT);

// enhance with a 'destroy' function
enableDestroy(server);

// some time later...
server.destroy(done);

如果打开连接不是问题,则可以按照本文中的说明简单地将完成函数传递给关闭函数server.close(done)

If open connections are not a problem you can simply pass the done function to the close function, server.close(done) as described in this post How to correctly unit test Express server

这篇关于运行茉莉花规格后关闭Express服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆