Как протестировать API RESTful CRUD с Mocha Chai на стороне сервера Node.js, если требуется вход в систему?

Я хочу протестировать логику CRUD на стороне сервера веб-приложений. Но только пользователь, вошедший в систему, может посетить веб-приложение.

if (res.locals.user){
  //CRUD functions here
} 

Я знаю, как использовать Mocha и Chai для тестирования этих функций CRUD без проверки входа в систему, но как я могу издеваться над пользователем входа в систему, чтобы проверить их? Использовать куки?


person Russj    schedule 08.08.2014    source источник
comment
Можете ли вы объяснить тип входа в систему?   -  person JME    schedule 08.08.2014
comment
Это просто пользователи, хранящиеся в mongoDB локально и использующие паспорт js.   -  person Russj    schedule 08.08.2014
comment
@Russj - ты решил это?   -  person Alex    schedule 14.08.2014


Ответы (2)


Обычно я делаю что-то вроде:

var request = require('supertest');

describe('My tests', function(){

    var agent = request.agent(app);

    //before all the tests run, log in
    before(function(done){
        request(app)
        .post('/login')
        .send({
            username: '[email protected]',
            password: 'password123'
        })
        .end(function (err, res) {
            if (err) { return done(err); }

            agent.saveCookies(res);

            done();
        });

    });

    it('Does something when logged in', function (done){
        var req = request(app).get('/account/something')
        .expect(200);

        //attach the logged in cookies to the agent
        agent.attachCookies(req);

        req.end(done);

        //assertions here
    });
})

Сначала отправьте запрос на вход, сохраните файлы cookie для агента.

Затем в запросах я хочу использовать аутентифицированный запрос. прикрепите к нему куки.

app – это экземпляр приложения Express.

person Alex    schedule 08.08.2014

@Russj, если предположить, что:

  • вы используете passport-local в качестве стратегии аутентификации passport
  • вы используете supertest для имитации вызовов API
  • у вас уже есть файл, который экспортирует ваше приложение Express

Тогда вот как я буду тестировать аутентифицированные конечные точки:

var request = require('supertest'),
    agent = request.agent();
    mongoose = require('mongoose'),
    // this examples assumes /path/to/your/app exports your Express app
    app = require('/path/to/your/app'), 
    // replace this with the model you use for authentication
    UserModel = mongoose.model('UserModel');
    // this example assumes your user model looks something like the following:
    // 
    //     UserModel = new mongoose.Schema({
    //       username:  String,
    //       password: String
    //     });

describe('testing authenticated end-point', function () {
    var UserModel, testuser;

    before(function (done) {

        // this is just to ensure we have a user to log in for your tests
        UserModel.findOneAndUpdate({ 
            { username: 'testuser' }, 
            { username: 'testuser', password: 'testpassword' }, 
            { upsert: true }, // this will create the user if it doesn't already exist
            function(err, doc) {
                testuser = doc
            }
        });

        // I assume /simulate-login is not an existing route in your app
        app.get('/simulate-login', function(req, res) {
            req.login(testuser); // .login is exposed in req by passport
        });

        // now we simulate login of our testuser and save  the cookies
        request(app)
            .get('/simulate-login')
            .end(function (err, res) {
                    if (err) { return done(err); }

                    // save cookies
                    agent.saveCookies(res);

                    done();
            });
    });

    // clean up after ourselves
    after(function () {
        UserModel.remove({ username: 'testuser' }).exec();
    });

    // now we can test an authenticated end-point as long as we attach the saved cookies
    it('should do whatever...', function (done) {
        var req;

        req = request(app)
            .get('/path/to/route/to/test')
            .expect(200);

        // attach cookies
        agent.attachCookies(req);

        // do your reqeust
        req.end(done);          
    });

});
person JME    schedule 09.08.2014