I have the following request that I need to test:
curl -H "Accept: application/json" -H "Content-type: application/json" -X POST -d '{"content":{"value":"18.5", "date": "20120413"}}' 'http://SERVER:PORT/marks'
I'm using expressjs and mocha. I did not find the way to add some header and specify some json parameters in a mocha's request:
it('Checks creation of a new mark', function(done){
request.post('http://SERVER:PORT/marks', function(err, response, body){
// Some headers and parameters should be set in the request
response.statusCode.should.equal(201);
done();
});
});
The test below (GET request) works well though:
it('Checks existence of marks for user dummyuser', function(done){
request.get('http://SERVER:PORT/user/dummyuser/marks', function(err, response, body){
response.statusCode.should.equal(200);
done();
});
});
UPDATE
The following works like a charm: (I though request what some kind of variable created by mocha).
request(
{ method: 'POST'
, uri: 'http://SERVER:PORT/marks'
, headers: { 'content-type': 'application/json' , 'accept': 'application/json' }
, json: { "content":{"value":"18,5", "date": "2012-04-13"} }
}
, function(err, response, body){
response.statusCode.should.equal(201);
done();
});
Take a look at the documentation. There is a great explaination of how to do a post with custom headers. One way of doing it which works for me could be the following.
var options = {
host: 'localhost',
port: 80,
path: '/echo/200',
method: 'POST',
headers: {
"X-Terminal-Id" : terminalId
}
};
var data = ""
var req = https.request(options, function(res) {
res.on('data', function(d) {
data += d;
});
res.on('end', function(err){
//Check that data is as expected
done(null, data)
})
});
req.end();
req.on('error', function(err) {}
done(err)
});