如何模拟来自http.request(nodejs,jasmine,sinon)的响应

我写了一个小的node模块,使得一个http请求,我有麻烦testing它。
有问题的代码如下所示:

 module.exports = (function () { var http = require("http"), Promise = require("promise"); var send = function send(requestOptions, requestBody) { return new Promise(function (resolve, reject) { http.request(requestOptions, function (response) { var responseChunks = []; response.on('data', function (chunk) { responseChunks.push(chunk); }); response.on('end', function () { resolve(Buffer.concat(responseChunks)); }); response.on('error', function (e) { reject(e); }); }).end(requestBody); }); }; return { send: send } 

我试图testing我的send方法,特别是由http.request调用的callback函数。
我需要做的是从http.request模拟或存根response对象,这样我就可以testingcallback函数的执行了。 但我无法弄清楚如何做到这一点。

如果它有任何相关性,我正在使用node v4.1, jasmine v2.3和sinon v1.17

试试诺克 。 在testing用例中嘲笑http请求是非常好的。

摩卡testing框架的工作和Should.JS(断言库)是相当不错的。

请参阅入门部分: https : //mochajs.org/

基本上,你使用mocha框架来创buildtesting用例。 然后你使用should.js节点模块来作出断言(关于应该发生什么的事实)。

你可以通过npm install mochanpm install should

摩卡testing文件代码:

 module.exports.run = function() { var chalk = require('chalk'); var should = require('should'); var http = require("http"); describe('test lib description', function(done){ it('Individual Test Case description', function(done) { function send(requestOptions, requestBody) { return new Promise(function (resolve, reject) { http.request(requestOptions, function (response) { var responseChunks = []; // Assertions using Should.JS // Example: The http status code from the server should be 200 should.equal(response.statusCode , 200); response.should.have.property('someProperty'); response.should.have.property('someProperty','someVal'); response.on('data', function (chunk) { responseChunks.push(chunk); done(); // Needed To tell mocha we are ready to move on to next test }); response.on('end', function () { resolve(Buffer.concat(responseChunks)); done(); }); response.on('error', function (e) { reject(e); done(); }); }).end(requestBody); }); }; }); }); } 

运行摩卡testing:

node ./node_modules/mocha/bin/mocha testFile

您可以尝试创build一个响应您的请求的本地或“模拟”服务器,而不是存根。 这避免了必须存储http.request。 本地服务器的好处之一就是无论您使用http.request,XMLHttpRequest还是类似的方法来获取在线资源,此方法都应该可以正常工作。

模拟服务器

你可以试试模拟服务器 。 有了它,你可以创build一个假的服务器来满足你的请求。

安装

 npm install mockserver-grunt --save-dev npm install mockserver-client --save-dev 

茉莉花代码

在您的规格(或testing)中,您可以使用以下(更改以满足您的需求):

 var mockServer = require("mockserver-grunt"); var mockServerClient = require("mockserver-client").mockServerClient; beforeAll(function(done) { // start the server mockServer.start_mockserver({ serverPort: 1080, verbose: true }); // setup how to respond let response = {name:'value'}; let statusCode = 203; mockServerClient("localhost", 1080).mockSimpleResponse('/samplePath', response, statusCode); setTimeout(function() { // give time for the mock server to setup done(); }, 4000); }); it("should be able to GET an online resource", function(done) { // perform tests, send requests to http://localhost:1080/samplePath } 

这将在端口1080上启动服务器。任何对http:// localhost:1080 / samplePath的请求都会收到提供的响应。

以类似的方式,可以在testing结束时closures服务器:

 afterAll(function() { mockServer.stop_mockserver({ serverPort: 1080, verbose: true }); }); 

其他说明

修复损坏的jar文件

当服务器首次启动时,它将尝试下载服务器所需的jar文件。 这是一次下载(据我所知)。 如果没有提供足够的时间,则不会完全下载,并且最终会生成无效或损坏的jar文件。 要解决这个问题,你可以自己下载jar文件。 该链接在运行中提供。 对我来说,这是位于https://oss.sonatype.org/content/repositories/releases/org/mock-server/mockserver-netty/3.10.6/mockserver-netty-3.10.6-jar-with-dependencies .jar 。 最有可能的是,你会想导航到最新版本。


更新

Express JS Server

自从我最初发布以来,我发现Express JS。 Express比Mock Server快速启动一个服务器实例。 你也不必担心jar文件。

安装

 npm install express --save-dev 

茉莉花代码

 var express = require('express'); var app = express(); var port = 3000; var server; beforeAll(function() { server = app.listen(port, function() { console.log("Listening on port " + port); }); app.get('/samplePath', function (req, res) { res.send("my response"); }); }); afterAll(function() { // shutdown server.close(); }); it("should be able to GET an online resource", function(done) { // perform tests, send requests to http://localhost:3000/samplePath } 

如果你想变得有趣,你可以返回你使用的path。 例如,如果你去http:// localhost:3000 / helloworld ,返回值将是helloworld。 你可以适应这个,以满足您的需求。

 app.get('/*', function (req, res) { res.send(req.params[0]); }); 

如果您需要将代码强制为错误path,则可以使用

 res.status(404) // HTTP status 404: NotFound .send('Not found'); 

来源: 如何以编程方式发送与Express / Node的404响应?