Подтвердить что ты не робот

Как связать http-звонки с суперагентом/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();
    });
);

Все, что мне не хватает здесь, или есть другой способ связать http-звонки с суперагентом?

4b9b3361

Ответ 1

Вызовы выполняются асинхронно, поэтому вам нужно использовать функции обратного вызова для их цепочки.

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

Ответ 2

Попытка поставить это в комментарии выше, форматирование не получилось.

Я использую async, который является действительно стандартом и работает очень хорошо.

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

Ответ 3

Это может быть наиболее элегантно решено с помощью promises, и там действительно полезная библиотека для использования 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) {
    // ... 
  });

Ответ 4

Я построил на Ответы по темпам, но вместо этого использовал 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();
        }
    );
});