2014-02-26 1 views
2

SailsJS 설정이 있고 단위 테스트를 실행하는 데 Mocha/Supertest/Superagent 조합을 사용하고 있습니다. 나는 supertest에 대해 읽었으며 세션과 쿠키를 저장하기 위해 superagent.agent ('url')를 확장하는 방법에 대해 읽었습니다. 내/운동 선수/로그인 및/선수/현재 경로는 제가 Postman을 사용하여 테스트 할 수 있고 올바른 값을 반환하는 것처럼 작동한다는 것을 알고 있습니다. 로그인 한 사용자의 세션에 로그인하고 확인SailsJS/Node, Mocha, Supertest를 사용하여 인증을위한 세션 저장소

1. 모카 테스트 : 테스트 할 때 그러나, 나는 현재 작업하고있는 무슨 여기

현재 로그인에 200 개 상태지만/운동 선수에 404 /되어 얻을에서

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

}, 

솔루션

난 당신이 '/ 운동 선수/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(); 
            }); 
         }); 
       }); 
     }); 
+0

안녕하세요, 당신의 문제에 대한 해결책을 찾으셨습니까? 나는 같은 종류의 문제에 직면하고있다. 미리 감사드립니다. – jmcollin92

+0

@ jmcollin92 - 아니, 여전히 같은 문제가 있습니다. 현재로서는 빌드를 통과했는지 확인하기 위해 테스트를 진행했습니다. 나는 Sails의 최신 베타 버전을 사용하기 시작했으며 결국에는 다시 구현하기 위해 (또는 적어도 시도하려고 노력하다가) – cgaubuchon

답변

1

확실하지 그래서 지금 기본적으로 위에서 '/ 운동 선수/현재 /'넣어 라우팅의 일부입니다 변경했다 이것에 대한 답을 찾았지만 다음 코드로 저장할 수있는 쿠키를 얻을 수있었습니다 :

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: "[email protected]",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(); 
    }); 
    }); 
}); 
+0

에이전트 변수 선언을 it 문으로 가져올 필요가 있지만 마침내 매우 거친 상태로 작동하게 만들었습니다. 지금. 그것이 sails/waterline의 0.10 베타 버전으로 수정 된 것이 었는지는 확실하지 않습니다. 지금 내 솔루션으로 OP를 업데이트합니다. – cgaubuchon