如何使用superagent / supertest连接http呼叫? [英] How to chain http calls with superagent/supertest?

查看:258
本文介绍了如何使用superagent / supertest连接http呼叫?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我在测试用例中无法获得多个请求,可以使用最高级。下面是我在一个测试用例中尝试的。但测试用例似乎只执行最后一次调用,即HTTP GET。

 它('应该响应GET添加项',function(done){
var agent = request应用程序)
agent.post('/ player')。type('json')。send({name:Messi});
agent.post('/ player' ('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();
});
);

我在这里缺少什么,还是有另一种方式用超级连接来连接http呼叫?

解决方案

调用是异步的,所以你需要使用回调函数来链接它们。



($)$($)$($)$($)$($)$($) '/ player')。type('json')。send({name:Messi})。end(function(){
agent.post('/ player' .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();
});
});
});
});


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?

解决方案

The calls are made asynchronous, so you need to use callback functions to chain them.

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

这篇关于如何使用superagent / supertest连接http呼叫?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆