2013-03-25 147 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) 
});