39 node.js express superagent supertest
我正在使用supertest测试一个快速API.
我无法在测试用例中获得多个请求以使用supertest.以下是我在测试用例中尝试过的内容.但测试用例似乎只执行最后一次调用,即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();
});
);
Run Code Online (Sandbox Code Playgroud)
我在这里缺少的任何东西,还是有另一种方式将http调用与superagent链接?
Tim*_*Tim 62
试图把它放在上面的评论中,格式化没有成功.
我正在使用异步,这是非常标准的,并且工作得非常好.
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);
});
Run Code Online (Sandbox Code Playgroud)
har*_*run 23
调用是异步的,因此您需要使用回调函数来链接它们.
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();
});
});
});
});
Run Code Online (Sandbox Code Playgroud)
小智 13
使用promises可以最优雅地解决这个问题,并且有一个非常有用的库可以使用supertest: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) {
// ...
});
Run Code Online (Sandbox Code Playgroud)
我建立在Tim的回复之上,但是使用它async.waterfall来对结果进行断言测试(注意:我在这里使用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();
}
);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23640 次 |
| 最近记录: |