[英]How to mock POST request using mock-http-server npm module in nodejs?
I am using 'chai-http' to test rest APIs and 'mock-http-server' to mock http requests. 我正在使用“ chai-http”来测试其余的API,并使用“ mock-http-server”来模拟http请求。 I am able to implement mock GET request by doing the following -
我可以通过执行以下操作来实现模拟GET请求-
it ('API GET TEST', function (done) { mockserver.on({ method: 'GET', path: '/v1/myAPI', reply: { status: 200, headers: {"content-type": "application/json"}, body: JSON.stringify(response) } }); chai.request(myapp) .get('/v1/myAPI') .end(function(err, res) { res.should.have.status(200); res.should.be.json; done(); }) });
My chai request correctly gets the response I have send from mockserver GET /v1/myAPI. 我的chai请求正确获取了我从模拟服务器GET / v1 / myAPI发送来的响应。
What I want to do is mock a post request and depending on post body I want to send response. 我想做的是模拟发布请求,并根据我要发送响应的发布主体。
mockserver.on({ method : 'POST', path : '/v1/myPOSTAPI', reply: { status: 200, headers: { "content-type": "application/json" }, body: function(req) { if (req.body.id == 1) { JSON.stringify(response1); } else { JSON.stringify({"error" : "Not Found"}); } } } });
My POST body is - 我的POST正文是-
{ id : 1 }
But when I use mock API for post, my 'req' object does not contain post body. 但是,当我使用模拟API进行发布时,我的“ req”对象不包含发布主体。 How can I get post body by mocking post request using 'mock-http-server' ?
如何通过使用'mock-http-server'模拟发布请求来获取发布正文?
https://github.com/spreaker/node-mock-http-server https://github.com/spreaker/node-mock-http-server
server.on({
method: 'POST',
path: ''/v1/myPOSTAPI'',
filter: function (req) {
return _.isEqual(req.body, {id : 1}) // use some function to equal req data
},
reply: {
status: 201,
headers: { "content-type": "application/json" },
body: function(req) {
if (req.body.id == 1) {
JSON.stringify(response1);
} else {
JSON.stringify({"error" : "Not Found"});
}
}
}
}); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.