我有一個node.js模塊,HTTP POSTS JSON請求,如何用mocha測試node.js http客戶端?
我想測試正確的網址,標頭,請求正文,並且實際執行請求。
我正在使用Mocha作爲測試框架。我如何測試它?
我有一個node.js模塊,HTTP POSTS JSON請求,如何用mocha測試node.js http客戶端?
我想測試正確的網址,標頭,請求正文,並且實際執行請求。
我正在使用Mocha作爲測試框架。我如何測試它?
嘗試SuperTest結合superagent。所有來自快遞的測試均使用SuperTest進行編寫。
例如:
var request = require('supertest')
, express = require('express');
var app = express();
app.get('/user', function(req, res){
res.send(201, { name: 'tobi' });
});
describe('GET /users', function(){
it('respond with json', function(done){
request(app)
.get('/user')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200, done);
})
})
您可以使用nock。你可以攔截http請求並且具有某些屬性
我已經使用了Sinon.js這種類型的東西。
sinon = require 'sinon'
assert = require "assert"
describe 'client', ->
describe '#mainRequest()', ->
it 'should make the correct HTTP call', ->
url = "http://some.com/api/blah?command=true"
request = {}
sinon.stub request, 'get', (params, cb) -> cb null, { statusCode: 200 }, "OK"
client = new MyHttpClient request
client.sendRequest()
assert.ok request.get.calledWith(url)
爲了簡化測試MyHttpClient類將一個請求對象作爲參數傳遞給構造函數。如果沒有提供,它只使用require'request'。
我正在考慮測試node.js http客戶端請求,而不是服務器.. –
@zemirco,我如何將實時應用服務器傳遞給此測試文件?我更喜歡與服務器分開運行測試。 –