【问题标题】:Session storage for authentication using SailsJS/Node, Mocha, Supertest使用 SailsJS/Node、Mocha、Supertest 进行身份验证的会话存储
【发布时间】:2014-03-29 23:09:10
【问题描述】:

我有一个 SailsJS 设置,并且正在使用 Mocha/Supertest/Superagent 组合来运行单元测试。我四处搜索并阅读了有关 supertest 以及它现在如何扩展 superagent.agent('url') 以存储会话和 cookie 的信息。我知道我的 /athlete/login 和 /athlete/current 路线正在工作,因为我可以使用 Postman 测试它们并且它们返回正确的值。但是,在测试时,我在登录时得到 200 状态,但在 /athlete/current 上得到 404

这是我目前正在使用的:

1. Mocha 测试登录并验证登录用户的会话

var should = require('should'),
    assert = require('assert'),
    request = require('supertest');

it('/athlete/login should return 200 and athlete on success', function (done){
                var athleteStub = AthleteStub(),
                    setPassword = athleteStub.password;

                Athlete.create(athleteStub, function(err, newAthlete) {
                    var user = request.agent(sails.express.app);

                    user
                            .post('/athlete/login')
                            .send({ 'email': athleteStub.email, 'password': setPassword })
                            .expect('Content-Type', /json/)
                            .end(function (err, res) {
                                if(err) return done(err);

                                console.log('test', user );

                                // res.should.have.status(200);
                                // res.body.email.should.equal(athleteStub.email);

                                user
                                    .get('/athlete/current')
                                    .set('Accept', 'application/json')
                                    .expect('Content-Type', /json/)
                                    .expect(200)
                                    .end(function (err, res) {
                                        if(err) return done(err);
                                        done();
                                    });


                            });
                });
            });

2。 /登录和/当前操作

login: function (req, res) {
    var bcrypt = require('bcrypt');

    Athlete.findOneByEmail(req.body.email).done(function (err, athlete) {
        if (err) {
            res.json({ error: 'DB error' }, 500);
        }

        if (athlete) {

            if ( !athlete.isActive ){
                res.json({ error: 'Your account is not active.' }, 500);
            }

            bcrypt.compare(req.body.password, athlete.password, function (err, match) {
                if (err){
                    res.json({ error: 'Server error' }, 500);
                }

                if (match) {
                    // password match
                    req.session.athlete = athlete.id;
                    res.json(athlete);
                } else {
                    // invalid password
                    if (req.session.athlete){
                        req.session.athlete = null;
                    }
                    res.json({ error: 'Invalid password' }, 403);
                }
            });
        } else {
            res.json({ error: 'User not found' }, 404);
        }
    });
},

current: function (req, res){

    if(req.session.athlete){
        Athlete.findOneById(req.session.athlete)
            .where({ isActive: true })
            .done(function(err, athlete) {
            if (err) {
                res.json({ error: 'No active athlete found with ID of '+req.params.id }, 404);
            } else {
                res.json(athlete);
            }
        });
    }else{
        res.json({ error: 'No active athlete currently logged in.' }, 404);
    }

},

解决方案

我改变了一些路由,所以基本上把上面的'/athlete/current/'现在是'/athlete/me/'

            it("/athlete/me should return user data if athlete is logged in", function(done){
            var agent = request.agent(sails.hooks.http.app),
                athleteStub = AthleteStub(),
                setPassword = athleteStub.password;

            agent
                .post('/athlete')
                .send( athleteStub )
                .expect('Content-Type', /json/)
                .end(function (err, res) {
                    should.not.exist(err);
                    res.should.have.status(200);
                    res.body.email.should.equal(athleteStub.email);
                    res.body.firstName.should.equal(athleteStub.firstName);
                    res.body.lastName.should.equal(athleteStub.lastName);

                    agent
                        .post('/athlete/login')
                        .send({ 'email': athleteStub.email, 'password': setPassword })
                        .expect('Content-Type', /json/)
                        .end(function (err, res) {
                            should.not.exist(err);
                            res.should.have.status(200);

                            agent
                                .get('/athlete/me')
                                .expect(200)
                                .end(function(err, res) {
                                        should.not.exist(err);

                                        res.body.email.should.equal(athleteStub.email);
                                        res.should.have.status(200);
                                        done();
                                    });
                        });
                });
        });

【问题讨论】:

  • 您好,您找到解决问题的方法了吗?我面临着同样的问题。提前致谢。
  • @jmcollin92 - 不,仍然有同样的问题。现在,我刚刚离开测试以确保我的构建通过。不过,我已经开始使用 Sails 的最新测试版,最终会再次实施(或至少尝试实施)

标签: node.js mocha.js sails.js supertest superagent


【解决方案1】:

不确定您是否找到了答案,但我能够使用以下代码保存 cookie:

var agent = request.agent(sails.hooks.http.app);

describe('Session', function(done) {
it("should be able to create", function(done) {


agent
  .post("/session/create")
  .send({email: "test.User1@gmail.com",password: "test", confirmation: "test"})
  .expect('set-cookie', 'cookie=hey; Path=/', done)
  .end(function(err, res) {
    console.log('got a response!! '+ JSON.stringify(res.body));
    done();
  });
});
it("should be logged in", function(done) {


agent
  .get("/user/index")
  .end(function(err, res) {
    console.log('got a response from user/index!! '+ JSON.stringify(res.body));
    done();
  });
  });
});

【讨论】:

  • 需要将代理变量声明带入 it 语句,但现在终于让它在一个非常粗糙的状态下工作。不确定这是否是 0.10 beta 版风帆/水线修复的问题。现在将使用我的解决方案更新 OP。
猜你喜欢
  • 1970-01-01
  • 2013-01-19
  • 2019-08-28
  • 2022-01-16
  • 2021-10-11
  • 2015-04-29
  • 2021-11-14
  • 2013-12-29
  • 2015-08-27
相关资源
最近更新 更多