2015-07-20 57 views
0

我希望能夠獲取某些響應屬性,並使用SuperTest有時將它們引入變量。我怎樣才能做到這一點?我沒有看到文檔做出任何反應的斷言。從SuperTest獲取特定的響應屬性

比如我想要做這樣的事情:

var statusCode = request(app).get(uri).header.statusCode; 

我想要做這樣的事情。因爲有時我喜歡將斷言拆分爲獨立的Mocha.js,所以它()測試是因爲我正在做BDD,所以這裏的'Thens'是基於預期的響應部分,所以每個測試都在檢查某種狀態在迴應中回來。

例如我想和supertest做到這一點:

var response = request(app).get(uri); 

it('status code returned is 204, function(){ 
response.status.should.be....you get the idea 
}; 

it('data is a JSON object array', function(){ 
}; 

回答

0

下面是一個例子,你如何完成你想要什麼:

服務器文件app.js

var express = require('express'); 
var app = express(); 
var port = 4040; 

var items = [{name: 'iphone'}, {name: 'android'}]; 

app.get('/api/items', function(req, res) { 
    res.status(200).send({items: items}); 
}); 

app.listen(port, function() { 
    console.log('server up and running at %s:%s', app.hostname, port); 
}); 

module.exports = app; 

test.js

var request = require('supertest'); 
var app = require('./app.js'); 
var assert = require('assert'); 

describe('Test API', function() { 
    it('should return 200 status code', function(done) { 
    request(app) 
     .get('/api/items') 
     .end(function(err, response) { 
     if (err) { return done(err); } 

     assert.equal(response.status, 200); 
     done(); 
     }); 
    }); 

    it('should return an array object of items', function(done) { 
    request(app) 
     .get('/api/items') 
     .end(function(err, response) { 
     if (err) { return done(err); } 
     var items = response.body.items; 

     assert.equal(Array.isArray(items), true); 
     done(); 
     }); 
    }); 

    it('should return a JSON string of items', function(done) { 
    request(app) 
     .get('/api/items') 
     .end(function(err, response) { 
     if (err) { return done(err); } 

     try { 
      JSON.parse(response.text); 
      done(); 
     } catch(e) { 
      done(e); 
     } 
     }); 
    }); 

}); 

您可以看到一些示例here on the superagent github library,因爲supertest基於superagent庫。