gpt4 book ai didi

Node.js - 简单的 Restify POST Mocha 测试失败

转载 作者:太空宇宙 更新时间:2023-11-03 22:48:12 25 4
gpt4 key购买 nike

我有一个简单的 Node.js Rest 服务器,其中包含使用 Restify 的单个 POST 服务。我正在尝试编写一个简单的 Mocha 测试,但它因超时而失败,尽管 REST 控制台测试(浏览器插件)成功。

我的服务器代码:

/**
* Module dependencies
*/

var restify = require('restify');
var events = require('events');
var util = require('util');


/**
* Create App
*/

var server = restify.createServer({
name: 'test',
version: '0.0.1'
});

var eventsEmitter = new events.EventEmitter();

/**
* Configuraion
*/

server.use(restify.acceptParser(server.acceptable));
server.use(restify.queryParser());
server.use(restify.bodyParser());


/**
* Routes
*/


server.post('/post', function (req, res, next) {
var text = "";
req.setEncoding("utf8");

req.on("data", function (chunk) {
text += chunk;
});
req.on("end", function () {
res.send(200, {ok: 'ok'});
});

return next();
});


/**
* Listen
*/

server.listen(8080, function () {
console.log('%s listening at %s', server.name, server.url);
});

Mocha测试如下:

var restify = require('restify');
var assert = require('assert');

// init the test client
var client = restify.createJsonClient({
url: 'http://127.0.0.1:8080',
version: '*'
});

describe('service: post endpoint', function() {

// Test #1
describe('200 response check', function() {
it('should get a 200 response', function(done) {
client.post('/post', { hello: 'world' }, function(err, req, res, data) {
if (err) {
throw new Error(err);
}
else {

if (data.code != 200) {
throw new Error('invalid response from /post');
}
done();
}
});
});
});

});

谁能告诉我为什么测试会超时(我已经在 Mocha 中增加超时进行了测试),但通过浏览器成功了?

最佳答案

问题是 Restify 在接收完请求后调用您的 server.post('/post', handler) 函数。您不必等待 dataend 事件。这是 Restify(以及其他类似的库,例如 Express)为您做的事情。所以你需要做的就是写

server.post('/post', function (req, res, next) {
res.send(200, {ok: 'ok'});
});

然后你就不应该有超时。您超时是因为您的处理程序正在等待已经到来的事件。

关于Node.js - 简单的 Restify POST Mocha 测试失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12989982/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com