我正在用supertest测试一个express API.

我无法在一个测试用例中获得多个请求来使用supertest.下面是我在测试用例中try 的内容.但测试用例似乎只执行最后一个调用,即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();
    });
);

我在这里遗漏了什么,或者有没有其他方法可以将http调用与superagent链接起来?

推荐答案

这些调用是异步的,因此需要使用回调函数来链接它们.

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

Node.js相关问答推荐

postgresql层与应用层的序列化

express返回意外的URL

NPM:无法导入本码模块

MongoDB的方面查询的Postgres类似功能

当变量在另一个文件中初始化时,在初始化错误之前无法访问变量

类扩展值[object object]不是构造函数或null

如何修复node.js中的错误代码无法加载资源:服务器响应状态为403(禁止)

NPM如何管理node_modules传递依赖?

如何使用包含条件正确分页的 sequelize 查询?

为什么 nginx 不将我的 react index.html 作为后备服务

为什么运行 yarn 命令会出错 - yargs-parser的完整性判断失败

无法关闭 node.js 中的mongoose 连接

使用正则表达式查找文档,但输入是数组

如何在没有云功能的情况下使用 Google PubSub

如何防止 node.js 中的内存泄漏?

node.js 中 res.setHeader 和 res.header 的区别

提供静态文件到底是什么意思?

Node_redis - 如何删除密钥?

npm 出现无法读取依赖项错误

Passport 的 req.isAuthenticated 总是返回 false,即使我硬编码 done(null, true)