简体   繁体   English

TDD测试第一个Node.js Express Rest Api-单元测试Middlewere /控制器/路由

[英]TDD Test first Nodejs express Rest Api - unit testing middlewere / controllers / routes

I'm trying to figure out how to test first my node js rest api app. 我试图弄清楚如何首先测试我的节点js rest api应用程序。 so far i've been using nock to intercept and mock any http call and by that test my service as a component. 到目前为止,我一直在使用nock拦截和模拟任何http调用,并以此来测试我作为组件的服务。 (component testing?) i want to start unit testing my app so my test pyramid is more balanced and tests will be easier to write. (组件测试?)我想开始对应用程序进行单元测试,以便我的测试金字塔更加平衡,并且测试将更容易编写。

searching the web i got to this approach: http://www.slideshare.net/morrissinger/unit-testing-express-middleware 我在网上搜索这种方法: http : //www.slideshare.net/morrissinger/unit-testing-express-middleware

var middleware = require('./middleware');
app.get('example/uri', function (req, res, next) {
  middleware.first(req, res)
    .then(function () { next(); })
    .catch(res.json)
    .done();
}, function (req, res, next) {
  middleware.second(req, res)
    .then(function () { next(); })
    .catch(res.json)
    .done();
});

(basicly pulling the middleware out and testing it) (基本上拉出中间件并对其进行测试)

since this presentation is from 2014 i was wondering what are the current up to date methods for unit testing express apps? 由于本次演讲是从2014年开始的,我想知道用于单元测试Express应用程序的最新方法是什么?

I had the same problem and I used another approach. 我遇到了同样的问题,因此我使用了另一种方法。 First I created a file included in all my tests that start node and export a function to send an http request: 首先,我创建了一个包含在所有测试中的文件,这些文件启动节点并导出函数以发送http请求:

process.env.NODE_ENV = 'test';
var app = require('../server.js');

before(function() {
  server = app.listen(3002);
});

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

module.exports = {
  app: app,
  doHttpRequest: function(path, callback) {
    var options = {
      hostname: 'localhost',
      port: 3002,
      path: path,
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Content-Length': 0
      }
    };

    var req = http.request(options, 
      function(response) {
        response.setEncoding('utf8');

        var data = '';
        response.on('data', function(chunk) {
          data += chunk;
        });

        response.on('end', function() {
          callback(data, response.statusCode);
        });
      });

    req.end();     
  }
}

Then I called my server using the previous declared method: 然后,我使用先前声明的方法调用了服务器:

var doHttpRequest = require('./global-setup.js').doHttpRequest;
var expect = require('chai').expect;

describe('status page test', function() {

  it('should render json', function(done){
    doHttpRequest('/status', function(response) {
      expect(JSON.parse(response).status).to.eql('OK');
      done();
    })
  });
});

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

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