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' ?
reqdoesn't containbodyfield inExpress.body-parser(or similar) parses the post data and puts it inreq.body. But, in case ofmock-http-server', they aren't parsing the body. Hence,req.bodyis empty. - Mukesh Sharmanockinstead. - Mukesh Sharma