我使用 Passport.js 进行身份验证(Facebook 策略)并使用 Mocha 和 Supertest 进行测试。我如何使用 Supertest for Facebook 策略创建 session 并发出经过身份验证的请求?
这是用户未登录时的示例测试:
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
最佳答案
这里看起来几乎没有什么不同,所以我将我的答案分为两部分。
1) 您首先必须通过 Facebook 创建测试用户。您可以通过以下两种方法之一执行此操作:1) Facebook 的图形 API,或 2) 通过应用程序的角色页面。
2) 与 SuperTest 保持 session 的推荐方法是使用称为 .agent() 的 SuperAgent 方法来保持 session 。 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 .
关于node.js - 如何使用 Passport/Facebook 策略/验证 Supertest 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20640774/