2016-08-17 19 views
1

我的快速应用程序中有一些中间件功能,它向外向服务器发出传出请求,然后将响应发送回客户端。Express中的中间件测试请求响应

所以这有点儿事:

var request = require('request'), 
    helpers = require('./helpers.js'); 

//GET 
module.exports.fetch = function(req, res) { 
    var options = helpers.buildAPIRequestOptions(req); 
    request(options, function(err, response, body){ 
    res.status(response.statusCode).send(body); 
    }); 
}; 

我期待在编写单元测试,并想模拟出当withing这些功能的传出请求被炒鱿鱼回到我自己的反应。

我所遇到supertest并在写一套房,像这样有一展身手:

var app = require('./index.js'), 
    request = require('supertest')(app), 
    should = require('should'); 

//GET 
describe('GET requests', function(){ 
    it('should do something', function(done){ 
    request 
     .get('/api/schemes') 
     .expect(200, done) 
     .end(function(err, res){ 
     // console.log(res); 
     // console.log(err); 
     res.status.should.equal(200); 
     }); 
    }); 
}); 

我想,我需要这样的东西兴农这里,这样我就可以窥探会打我的中间件功能的请求并返回我选择的答复。我只是在努力去理解如何在我的测试中添加残片。

有人可以提出进一步的建议吗?

由于

回答

2

node-nock可以记录经由http模块作出的请求(和如此,通过代理,请求)。然后这些可以排队等候在你的测试套件中重放。 GitHub页面有很棒的文档。

+0

nock是我用来嘲讽外部网络请求 –

+0

感谢您的建议,它看起来像是有用的东西,只是要弄清楚如何使用我在OP中共享的示例! :) – mindparse

+0

@mindparse抛出'nock.recorder.rec();'在请求之前,你会得到代码来模拟你刚才在控制台中得到的响应。 – Gant

相关问题