繁体   English   中英

单元测试ExpressJS应用程序

[英]Unit testing expressjs application

我有以下模块,我正在为其添加单元测试。 基本上,我想确保使用/和适当的处理程序this.express.static('www/html')调用app.listen ,我还想确保使用正确的端口调用app.listen

function WebService(express, logger) {
    this.express = express;
    this.log = logger;
    this.port = 3000;
}

// init routes and start the server
WebService.prototype.start = function start() {    
    var app = this.express();

    // Setup routes
    app.use('/', this.express.static('www/html'));

    // Startup the server
    app.listen(this.port);

    this.log.info('Starting webserver on port %s', this.port);

};

module.exports = WebService;

如果删除app.use(用简单的app.get代替),则可以通过将其传递到单元测试中的构造函数中来进行侦听测试

var express_stub = function() {
                var tmpObj = {
                    get: function() {},
                    listen: listen_stub // sinonjs stub
                };
                return tmpObj;
            };

当我切换到在路由中使用this.express.static时,结果就落空了(可能是因为this.express没有定义静态),我无法完全理解正确的处理方式。 作为构造函数的this.express()真的让我失望。 我无法弄清楚模拟要验证的电话的正确方法。

您可以使用Supertest

var request = require('supertest')
  , express = require('express');

var app = express();

app.get('/user', function(req, res){
  res.send(200, { name: 'tobi' });
});

request(app)
  .get('/user')
  .expect('Content-Type', /json/)
  .expect('Content-Length', '20')
  .expect(200)
  .end(function(err, res){
if (err) throw err;
  });

使用摩卡:

describe('GET /users', function(){
  it('respond with json', function(done){
    request(app)
      .get('/user')
      .set('Accept', 'application/json')
      .expect('Content-Type', /json/)
      .expect(200, done);
  })
})

我建议您将应用程序分为两个文件:包含所有应用程序代码的app.js并通过module.exports返回它;以及需要app.js并将其传递到新的http服务器监听方法的server.js文件。 这样,您可以编写需要执行app.js的测试。

这就是使用Express Generator创建的默认应用程序的工作方式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM