2013-03-25 84 views
0

我有以下要求,我需要测试:测试快递应用与摩卡

curl -H "Accept: application/json" -H "Content-type: application/json" -X POST -d '{"content":{"value":"18.5", "date": "20120413"}}' 'http://SERVER:PORT/marks' 

我使用expressjs和摩卡。我没有找到添加一些标题的方法,并在摩卡的请求中指定一些json参数:

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

});

下测试(GET请求)效果很好,但:

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

下面的作品就像一个魅力:(我虽然要求哪些类型的变量,由摩卡创建)。

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(); 
}); 
+0

你使用[request](https://github.com/mikeal/request)吗?如果是这样,请查看文档,它描述了如何设置标题以及如何将数据作为JSON发送。 – robertklep 2013-03-25 09:48:05

回答

2

看看documentation。有一个很好的解释如何做自定义标题的帖子。一种做法对我有用,可能是以下几种。

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