如何通过Passport / Facebook战略authenticationSupertest请求/?

我使用Passport.js进行身份validation(Facebook策略),并使用Mocha和Supertest进行testing。 我如何创build一个会话,并与Supertest Facebook的策略进行authentication的请求?

以下是用户未login时的示例testing:

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) 

谢谢你的build议:D

这里有几个不同的东西,所以我把我的答案分为两部分。

1)您首先必须通过Facebook创buildtesting用户。 您可以通过以下两种方法之一完成:1)Facebook的Graph API,或2)通过应用程序的Roles页面。

2)使用SuperTest持久会话的推荐方法是使用称为.agent()的SuperAgent方法来持久会话。 你可以用SuperAgent做任何事情,你可以用SuperTest做。 看到这个Github的post了解更多。

 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上还有其他一些很好的代码片段。 请在这里find他们。

一般的解决scheme是创build一个将在请求之间重用的cookie jar。

下面的例子不是特定的护照,但应该工作:

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

这个例子显示了如何做testing的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(); }); }); 

这里有一个关于它的博客文章 。