2013-12-17 12 views
6

私はPassport.jsを認証(Facebook戦略)に使用しており、MochaとSupertestでテストしています。 Facebook戦略のためにセッションを作成し、認証されたリクエストをSupertestで作成するにはどうしたらいいですか?ここでPassport/Facebook戦略/でSupertestリクエストを認証する方法

はユーザーがログインしていないときのためのサンプルテストです:

describe 'when user not logged in', -> 

    describe 'POST /api/posts', -> 
     it 'respond with 401', (done)-> 
     request(app). 
      post(API.url('posts')). 
      set('Accept', 'application/json'). 
      send(post: data). 
      expect('Content-Type', /json/). 
      expect(401, done) 

アドバイスをありがとう:D

答えて

12

いくつかの異なるものがあり、ここでは次のようになりますので、私は二つの部分に私の答えを分けました。

1)まず、Facebookからテストユーザーを作成する必要があります。あなたは、1)FacebookのグラフAPI、または2)あなたのアプリケーションのRolesページを通しての2つの方法の1つを使ってそうすることができます。

2)SuperTestでセッションを永続化するには、セッションを維持するために.agent()というSuperAgentメソッドを使用することをお勧めします。 SuperAgentでできることは何でも、SuperTestで行うことができます。詳しくは、Github投稿を参照してください。

var supertest = require('supertest'); 
var app = require('../lib/your_app_location'); 

describe('when user not logged in', function() { 
    describe('POST /api/posts', function() { 
     var agent1 = supertest.agent(app); 

     agent1 
      .post(API.url('posts')) 
      .set('Accept', 'application/json') 
      .send(post: data) 
      .(end(function(err, res) { 
       should.not.exist(err); 
       res.should.have.status(401); 
       should.exist(res.headers['set-cookie']); 
       done(); 
      })); 
    }); 
}); 

VisionMedia Githubには他にも優れたコードスニペットがいくつかあります。それらを見つけてくださいhere

+0

ありがとうございます。あなたの答えは私を大いに助けました:D – Zeck

+0

あなたはfacebookで認証する方法の例を示すことができますか?つまりログインをどのように実行するのですか?私は多分何かを逃しているように感じる。 – Kilizo

2

一般的な解決策は、リクエスト間で再利用されるクッキージャーを作成することです。

次の例では、パスポートの特定ではありませんが、動作するはずです:

var request = require('request'); 

describe('POST /api/posts', function() { 
    // Create a new cookie jar 
    var j = request.jar(); 
    var requestWithCookie = request.defaults({jar: j}), 

    // Authenticate, thus setting the cookie in the cookie jar 
    before(function(done) { 
     requestWithCookie.post('http://localhost/user', {user: 'foo', password: 'bar'}, done); 
    }); 

    it('should get the user profile', function (done) { 
     requestWithCookie.get('http://localhost/user', function (err, res, user) { 
      assert.equal(user.login, 'foo'); 
      done(); 
     }); 
    }); 
}); 
+0

ローカル戦略のこの解決策ですか?または基本認証? –

0

このexampleは、テストのSuperTestの一部を行う方法を示しています

describe('request', function() { 
    describe('persistent agent', function() { 
    var agent1 = request.agent(); 
    var agent2 = request.agent(); 
    var agent3 = request.agent(); 
    var agent4 = request.agent(); 

    it('should gain a session on POST', function(done) { 
     agent3 
     .post('http://localhost:4000/signin') 
     .end(function(err, res) { 
      should.not.exist(err); 
      res.should.have.status(200); 
      should.not.exist(res.headers['set-cookie']); 
      res.text.should.include('dashboard'); 
      done(); 
     }); 
    }); 

は、ここでそれについてblog postです。

関連する問題