How to chain http calls with superagent/supertest?

user3189921 picture user3189921 · Jan 13, 2014 · Viewed 27.8k times · Source

I am testing an express API with supertest.

I couldn't get multiple requests in a test case to work with supertest. Below is what i tried in a test case. But the test case seem to only execute the last call which is the 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();
    });
);

Anything i am missing here, or is there another way to chain http calls with superagent?

Answer

Tim picture Tim · Sep 20, 2014

Tried to put this in a comment above, formatting wasn't working out.

I'm using async, which is really standard and works really well.

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);
});