如何使用superagent / supertest链接http调用?

我正在用超级testing一个快速API。

在testing用例中,我无法获得多个请求来处理超级用户。 以下是我在testing用例中尝试的内容。 但是testing用例似乎只执行最后一次调用,即HTTP GET。

it('should respond to GET with added items', function(done) { var agent = request(app); agent.post('/player').type('json').send({name:"Messi"}); agent.post('/player').type('json').send({name:"Maradona"}); agent.get('/player').set("Accept", "application/json") .expect(200) .end(function(err, res) { res.body.should.have.property('items').with.lengthOf(2); done(); }); ); 

我在这里失踪的任何东西,还是有另一种方法链接与superagent http调用?

这些调用是asynchronous的,所以你需要使用callback函数来链接它们。

 it('should respond to GET with added items', function(done) { var agent = request(app); agent.post('/player').type('json').send({name:"Messi"}).end(function(){ agent.post('/player').type('json').send({name:"Maradona"}).end(function(){ agent.get('/player') .set("Accept", "application/json") .expect(200) .end(function(err, res) { res.body.should.have.property('items').with.lengthOf(2); done(); }); }); }); }); 

试图把这个在上面的评论,格式不行。

我正在使用asynchronous,这是非常标准的,工作得很好。

 it('should respond to only certain methods', function(done) { async.series([ function(cb) { request(app).get('/').expect(404, cb); }, function(cb) { request(app).get('/new').expect(200, cb); }, function(cb) { request(app).post('/').send({prop1: 'new'}).expect(404, cb); }, function(cb) { request(app).get('/0').expect(200, cb); }, function(cb) { request(app).get('/0/edit').expect(404, cb); }, function(cb) { request(app).put('/0').send({prop1: 'new value'}).expect(404, cb); }, function(cb) { request(app).delete('/0').expect(404, cb); }, ], done); }); 

这可以用promise来最优雅的解决,而且还有一个真正有用的库来使用supertest的promise: https ://www.npmjs.com/package/supertest-as-promised

他们的例子:

 return request(app) .get("/user") .expect(200) .then(function (res) { return request(app) .post("/kittens") .send({ userId: res}) .expect(201); }) .then(function (res) { // ... }); 

我build立在Tim的回复 async.waterfall ,但使用了async.waterfall ,以便能够对结果进行断言testing(注意:我在这里使用Tape而不是Mocha):

 test('Test the entire API', function (assert) { const app = require('../app/app'); async.waterfall([ (cb) => request(app).get('/api/accounts').expect(200, cb), (results, cb) => { assert.ok(results.body.length, 'Returned accounts list'); cb(null, results); }, (results, cb) => { assert.ok(results.body[0].reference, 'account #0 has reference'); cb(null, results); }, (results, cb) => request(app).get('/api/plans').expect(200, cb), (results, cb) => request(app).get('/api/services').expect(200, cb), (results, cb) => request(app).get('/api/users').expect(200, cb), ], (err, results) => { app.closeDatabase(); assert.end(); } ); });