2015-07-20 61 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库。