1
votes

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' ?

1
Generally, req doesn't contain body field in Express. body-parser (or similar) parses the post data and puts it in req.body. But, in case of mock-http-server', they aren't parsing the body. Hence, req.body is empty. - Mukesh Sharma
Try nock instead. - Mukesh Sharma

1 Answers

1
votes

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"});
                }
            }
}

});