grunt测试api与最高,快递和摩卡 [英] grunt testing api with supertest, express and mocha

查看:240
本文介绍了grunt测试api与最高,快递和摩卡的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由快递运行的https服务器,我使用摩卡和supertest来测试。



我的问题是 - 如果我只运行测试 - 它的确定。如果我尝试运行gruntfile与测试,然后运行快递 - 我看到很多EADDRINUSE错误,即使在测试文件我做了after()与app.close()。
同样适用于测试任务。



这是我的exapmle测试:

  / * jshint node:true * / 
/ *全局描述,之后* /
(function(){
'use strict';
process.env.NODE_TLS_REJECT_UNAUTHORIZED =0;
var request = require('supertest');
var app = require('../ server.js')app;
var expect = require('chai')。expect;
var Cookies;

after(function(done){
app.close();
setTimeout function(){done();},1500);
});

describe('/ login',function(){
it ',function(done){
request(app)
.post('/ login')
.send({login:test,password:'test'})
.expect(302)
.end(function(err,res){
expect(err).to.be.equal(null);
expect(res.te xt).to.be.equal(暂时移动重新定向到/);
Cookies = res.headers ['set-cookie']。pop()。split(';')[0];
done();
} );

});
//用于为angualar工厂提供会话数据的测试API
describe('/ api / session',function ){
it('应该返回JSON中的会话数据',function(done){
var req = request(app).get('/ api / session');
req。 cookie = Cookies;
req.set('Accept','application / json')
.end(function(err,res){
expect(err).to.be.equal (null);
expect(res.body).to.have.property(_ id);
done();
});
});
});

}());

那些测试还远远不够完美,我刚刚通过适当的软件测试开始我的冒险。



所有这些已经在使用的端口都是显而易见的,而且没有任何问题。所有测试工作正常,服务器工作正常,但stdout是疯狂的。这种行为远非理想,可能充满潜在的问题和不稳定性问题。



我的问题是 - 如何摆脱它?



我的想法是:




  • 在不同端口上创建专用服务器进行测试。不幸的是,我不得不提示如何实现这一点。


  • 使一些条件为superagent运行服务器,如果它没有运行,或只是...传递给超级用户否则


  • 使用别的东西,然后是超级用户(如请求,但不知道所有的cookies和node_tls_reject_una是否可以正常工作。




正如你所看到的那样,我为这个话题奋斗,提出的问题比答案多,而且没有足够的经验知道在哪里看。 p>

我非常感谢任何帮助。



编辑:



我发现,我可以做:

  before(function(done){
app.listen(3001, function(){done();});
});

在另一个端口上,但是整个server.js加载了,所以它也开始,然后,当与运行的服务器一起触发时,有明显的EADDRINUSE。

解决方案

当使用 superagent 时,您应该总是传递已配置的Express应用程序(中间件注册,控制器路由等),但不会初始化为HTTP服务器它会为您做到这一点,并将通过 http.createServer 推迟,到操作系统选择一个可用的端口。



如果你目前拥有这个 server.js 模块已经提供了一个完整的HTTP服务器的静态实例,这很可能是您的问题的根源。在任何一种情况下,尝试从实际的服务器实例中提取应用程序配置/引导,如下所示:

  // server.js 
var express = require('express');
var middleware = require('./中间件');
var controllers = require('./ controllers');

//配置Express应用程序实例。
exports.setup = function(app){
app.use(middleware.foo);
app.get('/ bar',controllers.bar);

app.locals.baz ='quux';
}

//如果您的应用程序的某些部分在`server.app`的静态引用上依赖
//,您可能会在脚下拍摄自己。
exports.app = setup(express());
exports.app.listen(3000);

然后,在您的测试中,您可以按照以下方式执行某些操作:

  // tests.js 
var express = require('express');
var server = require('./ server');

describe('Server tests',function(){
//在每个测试之前创建一个新的服务器实例
beforeEach(function createNewSever(){
this .app = server.setup(express());
});

describe('Foo',function(){
it('barrs',function {
request(this.app)//初始化端口A上的服务器实例
// ... supertests
});

it('bazzes' ,function(){
request(this.app)//初始化端口B上的服务器实例
// ... more supertests
});
});
});

这只是为了说明的目的,实例化应用程序实例的时间/方式将取决于您的测试上下文。重要的是要为您的测试用例创建新鲜,干净,独立和隔离的服务器实例。如果您使用测试运行器并行或以随机顺序执行测试是绝对必要的。


I have an https server running by express, which i test using mocha and supertest.

My problem is - if i run only the test - its ok. If i try to run gruntfile with test then run express - i see lot of EADDRINUSE errors, even if in test files i do after() with app.close(). Same applies to watch task on tests.

Here is my exapmle test:

/* jshint node: true*/
/*global describe, it, after*/
(function() {
    'use strict';
    process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
    var request = require('supertest');
    var app = require('../server.js').app;
    var expect = require('chai').expect;
    var Cookies;

    after(function(done) {
        app.close();
        setTimeout(function(){done();}, 1500);
    });

    describe('/login', function() {
        it('should auth the user', function(done) {
            request(app)
                .post('/login')
                .send({login: "test", password: 'test'})
                .expect(302)
                .end(function(err, res) {
                    expect(err).to.be.equal(null);
                    expect(res.text).to.be.equal("Moved Temporarily. Redirecting to /");
                    Cookies = res.headers['set-cookie'].pop().split(';')[0];
                    done();
            });

        });
    });
    // testing API for serving session data for angualar factory
    describe('/api/session', function() {
        it('should return session data in JSON', function(done) {
            var req = request(app).get('/api/session');             
                req.cookies = Cookies;
                req.set('Accept','application/json')
                .end(function(err, res) {
                    expect(err).to.be.equal(null);
                    expect(res.body).to.have.property("_id");
                    done();
            });
        });
    });

}());

Im aware that those test are far from perfect. Im just beginning my adventure with proper software testing.

All those "port already in use" are obvious, and none of them... give any issue. all tests work fine, server works fine, but stdout is crazy. Such behaviour is far from ideal, and probably full of potential problems and unstability issues.

My question is - how to get rid of it?

My ideas are:

  • create dedicated server for test on just different port. Unfortunately i have to clue how to implement this.

  • make some conditional for superagent to run server if it is not running, or just... pass it to superagent otherwise?

  • use something else then superagent (like request, but im not sure if all the cookies and node_tls_reject_unauthorized would work.

As You can see - i struggle with that topic and have more questions than answers, and not enough experiance to know where to look at.

I kindly appreciate any help.

EDIT:

I found, that i can do:

before(function(done) {
    app.listen(3001, function() { done(); });
});

which starts test on another port but... the whole server.js is loaded anyway, so it starts anyway too. Then, when firing it together with running server, there is obvious EADDRINUSE.

解决方案

When using superagent, you should always pass it an Express application which has been configured (middleware registered, controllers routed, etc.)--but not initialized as a HTTP server. It will do that for you and it will defer, through http.createServer, to the OS to pick an available port.

If you currently have that the server.js module is already providing a static instance of a full-blown HTTP server, that is most likely the source of your problems. In either case, try extracting the application configuration/bootstrapping from the actual server instantiation like so:

// server.js
var express = require('express');
var middleware = require('./middleware');
var controllers = require('./controllers');

// Configures the Express application instance.
exports.setup = function (app) {
    app.use(middleware.foo);
    app.get('/bar', controllers.bar);

    app.locals.baz = 'quux';
}

// You might shoot yourself in the foot if parts of your application depend
// on a static reference at `server.app`.
exports.app = setup(express());
exports.app.listen(3000);

Then, in your tests, you can do something along the lines:

// tests.js
var express = require('express');
var server = require('./server');

describe('Server tests', function () {
    // Create a fresh server instance prior to each test
    beforeEach(function createNewSever() {
        this.app = server.setup(express());
    });

    describe('Foo', function () {
        it('barrs', function () {
            request(this.app)  // initializes a server instance on port A
            // ... supertests
        });

        it('bazzes', function () {
            request(this.app)  // initializes a server instance on port B
            // ... more supertests
        });
    });
});

This is just for illustrative purposes, where the when/how of instantiating the application instance will depend on your test context. The important thing to take away is that you should be able to create fresh, clean, independent and isolated server instances for your test cases. It is an absolute necessity should you use a test runner that executes tests in parallel or in a random order.

这篇关于grunt测试api与最高,快递和摩卡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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