I am using 'chai-http' to test rest APIs and 'mock-http-server' to mock http requests. I am able to implement mock GET request by doing the following -
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.
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 -
{ id : 1 }
But when I use mock API for post, my 'req' object does not contain post body. How can I get post body by mocking post request using '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"});
}
}
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.