TDD先testingNodejs表示Rest Api – unit testing中间件/控制器/路由

我想弄清楚如何testing我的节点jsrestAPI应用程序。 到目前为止,我一直在使用nock拦截和模拟任何http调用,并通过testing我的服务作为一个组件。 (组件testing?)我想开始unit testing我的应用程序,所以我的testing金字塔更平衡,testing将更容易编写。

searchnetworking我得到了这种做法: 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(); }); 

(基本上拉出中间件并testing它)

因为这个演示文稿是从2014年我想知道什么是当前最新的unit testing快递应用程序的方法?

我有同样的问题,我用另一种方法。 首先,我创build了一个包含在我的所有testing中的文件,该文件启动节点并导出一个函数发送一个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(); } } 

然后我使用之前声明的方法调用我的服务器:

 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(); }) }); });