【问题标题】:SailsJs :: Keep sessions with mochaSailsJs :: 与 mocha 保持会话
【发布时间】:2015-01-16 05:04:25
【问题描述】:

我需要在 mocha 请求之间保持会话活跃。

登录后,我将用户ID存储在快速会话对象中:

req.session.user = user.id ;

在浏览器上,会话保持不变,不需要任何问题(使用 Postman 测试)。

但是,我需要使外部应用程序可以访问我的 REST API,并且我不希望对我的 API 上的每个请求进行身份验证。

有没有办法让我能够在 mocha 中或通过 API 的客户端应用程序保持两个请求之间的会话?

提前致谢。

英语不是我的母语,我可能没有我想要的那么清楚。因此,我可以提供您可能需要的任何信息来帮助我。

更新

感谢 Alberto,我找到了如何通过 Supertest 在 Mocha 中保持我的会话活力。 代理会保留他的会话,直到它被销毁或请求注销。 需要做的是使用相同的代理登录和请求 API。

我所做的是:

var request = require('supertest'),
    should = require('chai').should();

describe('ImageController', function() {
  var agent = request.agent('http://localhost:1337') ;

  before(function(done){
      agent
        .post('/auth/local')
        .send({identifier: 'email', password: 'password'})
        .end(function(err, res) {
          if (err) return done(err);

          done();
        });
  })

  after(function(done){
      agent
        .get('/logout')
        .end(function(err, res) {
          if (err) return done(err);

          done();
        });
  })
  describe('POST /image', function(){
    it('should return 201 for image creation after login', function (done) {
      agent
        .post('/image')
        .send({name: 'test.png'})
        .end(function (err, res) {
          if (err) return done(err);

          res.status.should.be.equal(201);
          done();
        });
    });
  });
});

【问题讨论】:

标签: session express sails.js mocha.js passport.js


【解决方案1】:

使用超测代理功能如何存储cookie。

在超测文档中有一个示例:https://github.com/tj/supertest#example

带有超级测试示例的 Sails.js 示例:https://github.com/albertosouza/sails-test-example

测试文件示例代码:

var request = require('supertest');
var assert = require('assert');
var authenticated;

describe('Example test', function() {
  // use efore all to create custom stub data
  before(function(done) {
    // use supertest.agent for store cookies ...
    // logged in agent

    // after authenticated requests 
    //login and save one agent with your session cookies. Ex:
    authenticated = request.agent(sails.hooks.http.app);
    authenticated.post('/auth/login')
    .send({
      email: user.email,
      password: user.password
    })
    .end(function(err) {
      done(err);
    });
  });

  describe('authenticated requests', function(){
    it ('should access one protected route', function(done){
      // use the authenticated agent to do authenticated requests
      authenticated.get('/protected')
      .expect(200)
      .end(function(err, res) {
        if (err) return done(err);

        console.log('response:', res.text);

        done();
      });
    });
  });
});

【讨论】:

  • 感谢您的回答。我会尽快检查的。
  • Github 链接已损坏。您可以将相关的 sn-p 粘贴到您的答案中吗?
  • @Jamil 完成,看看是否有帮助,我有一个带有sails 0.10 的sails.js 示例:github.com/albertosouza/sails-test-example
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-29
  • 2011-04-10
  • 2016-12-13
相关资源
最近更新 更多