如何使用Passport / Facebook策略验证Supertest请求/?

时间:2013-12-17 17:26:31

标签: node.js express mocha passport.js supertest

我正在使用Passport.js进行身份验证(Facebook策略)并使用Mocha和Supertest进行测试。如何使用Supertest for Facebook策略创建会话并进行经过身份验证的请求?

以下是用户未登录时的示例测试:

  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

3 个答案:

答案 0 :(得分:12)

这里几乎没有什么不同的东西,所以我将我的答案分为两部分。

1)您首先必须通过Facebook创建测试用户。您可以通过以下两种方法之一来实现:1)Facebook的Graph API,或2)通过应用程序的角色页面。

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

答案 1 :(得分:2)

一般的解决方案是创建一个将在请求之间重用的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();
        });
    });
});

答案 2 :(得分: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