[英]How to mock POST request using mock-http-server npm module in nodejs?
我正在使用“ chai-http”來測試其余的API,並使用“ mock-http-server”來模擬http請求。 我可以通過執行以下操作來實現模擬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(); }) });
我的chai請求正確獲取了我從模擬服務器GET / v1 / myAPI發送來的響應。
我想做的是模擬發布請求,並根據我要發送響應的發布主體。
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"}); } } } });
我的POST正文是-
{ id : 1 }
但是,當我使用模擬API進行發布時,我的“ req”對象不包含發布主體。 如何通過使用'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.