如何在Sails JS中使用Mocha对Google OAuth Passport进行单元测试

6

我现在正试图测试我的控制器,需要访问session。我发现可以使用superagent进行登录,但我的唯一选项是通过google oauth登录Web应用程序,目前我找不到任何适用于Mocha测试的合适示例。有什么帮助吗?

1个回答

1
这取决于您如何实现会话。
在我的Sails应用程序中,经过身份验证后,我设置了req.session.authenticated = true,以及cookie等。如果您正在执行类似的操作,则可以在您的/login路由中添加以下内容:
if (process.env.NODE_ENV === 'test') {
  req.session.authenticated = true;
  // do what you would do next after authentication
} else {
  // do normal login procedures
}

然后,在您的测试中,您可以在before钩子中使用superagent/login路由发送请求进行身份验证:

describe('MyController', function() {
  var agent;

  before(function (done) {
    agent = require('superagent').agent('YOUR_APP_URL');

    // authenticate
    agent
      .post('/login')
      .end(done)
  });

  // in your tests, use the same agent to make future requests
  describe('#someAction', function() {
    it('should do something', function(done) {
      agent.
        .post('someAction')
        .end(function (err, res) {
          // should work!
        });
    });
  });
});

这只是一个想法 - 你可以根据自己的会话检查方式进行调整。这适用于我使用 Mocha 进行测试的 Sails 应用程序。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接