Node.js   发布时间:2022-04-24  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了node.js – 使用Mocha和Chai测试Express和Passport OAuth2大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个使用Express和Passport的应用程序.我在Passport中使用Google OAuth2策略.我有一些需要通过此策略登录的路线.

我目前正在与Mocha和Chai进行集成测试,但我不确定如何绕过或使用某些路由所需的OAuth2身份验证.

例如,这是我的一个测试:

it("should list a single item on /items/<id> GET",function(donE) {                                                                             
  chai.request(server)
    .get('/items/' + id) 
    .end(function(err,res) {
      res.should.have.status(200);
      res.should.be.json;
      res.body.should.be.a('object');
      res.body.should.have.property('description');
      done();
    }); 
});@H_801_7@ 
 

我的路线为/ items /:id

router.get('/items/:id',auth.isLoggedIn,function(req,res) {
  var item = getItem();
  res.json(item);
});@H_801_7@ 
 

/ items /:id需要登录.有没有办法绕过登录进行测试,或者模仿用户,我的集成测试会起作用?

解决方法

我能用mocha chai chai-http nock和nock-github-oauth测试github OAuth /护照

nock-github-oauth存根令牌网址

还手动将github用户和电子邮件api调用与GitHub api文档中的示例一起锁定

这是我的auth_controller_spec.js

//During the test the env variable is set to test
process.env.NODE_ENV = 'test';

var chai = require('chai');
var chaihttp = require('chai-http');
var should = chai.should();
var expect = chai.expect

var User = require.main.require('models/User');

// https://gist.github.com/brAnneman/8048520#7-the-wrapper
var app = require.main.require('app');

chai.use(chaihttp);


function nockGitHubUserAPI(nock) {
  /**
   * Intercept `https://api.github.com:443/user` API Call.
   */
   nock('https://api.github.com:443')
    .filteringPath(/\/user.+/,'/user')
    .get('/user')
    .reply(200,{
        "login": "octocat","id": 1,"avatar_url": "https://github.com/images/error/octocat_happy.gif","gravatar_id": "","url": "https://api.github.com/users/octocat","html_url": "https://github.com/octocat","followers_url": "https://api.github.com/users/octocat/followers","following_url": "https://api.github.com/users/octocat/following{/other_user}","gists_url": "https://api.github.com/users/octocat/gists{/gist_iD}","starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}","subscriptions_url": "https://api.github.com/users/octocat/subscriptions","organizations_url": "https://api.github.com/users/octocat/orgs","repos_url": "https://api.github.com/users/octocat/repos","events_url": "https://api.github.com/users/octocat/events{/privacy}","received_events_url": "https://api.github.com/users/octocat/received_events","type": "User","site_admin": false,"name": "monalisa octocat","company": "GitHub","blog": "https://github.com/blog","LOCATIOn": "San Francisco","email": "octocat@github.com","hireable": false,"bio": "There once was...","public_repos": 2,"public_gists": 1,"followers": 20,"following": 0,"created_at": "2008-01-14T04:33:35Z","updated_at": "2008-01-14T04:33:35Z"
      }
    );

/**
 * Intercept `https://api.github.com:443/user/emails` API Call.
 */
  nock('https://api.github.com:443')
    .filteringPath(/\/user\/emails.+/,'/user/emails')
    .get('/user/emails')
    .reply(200,[
        {
          "email": "octocat@github.com","verified": true,"priMary": true
        }
      ]
    );
}


describe('Auth Controller',(donE) => {

  var user,nock,github,mockToken,githubHost;

  before((donE) => {
    nock = require('nock');
    nock.enableNetConnect('127.0.0.1');
    github = require('nock-github-oauth');

    nockGitHubUserAPI(nock)

    github.nock(donE);
  })

  beforeEach((donE) => { //Before each test we reset the database
    User.query().del().then(() => {
      var params = {name: 'bonzo',authtype: 'github',authid: '12345678'}
      // Create a user so the db isn't empty
      // May Help us uncover odd bugs
      new User(params).save()
        .then((bonzo) => {
          user = bonzo;
          done();
        })
    })
  });

  after(function(donE) {
      nock.cleanAll();
      done();
  });

  describe('github link',() => {
      it('it should redirect to github.com login / approve page',(donE) => {
        chai.request(app)
            .get('/auth/github')
            .redirects(0)
            .end((err,res) => {
              expect(res.headers['LOCATIOn']).to.match(/^https:\/\/github.com\/login\/oauth\/authorize/);
              done();
            });
      });
  });

  describe('github callBACk',() => {
      it(' should poll github api for details,upsert the user and log them in',(donE) => {
        var agent = chai.request.agent(app)
          agent.get('/auth/github/callBACk')
            .query({Code : '9835b716e83875665b21' })
            .end((err,res) => {
              // If @R_675_6048@sful layout displays username on page in (brackets)
              expect(res.text).to.match(/\(octocat\)/);
              done();
            });
      });
  });


  describe('logout',() => {
      it('it should end the session and show login',(donE) => {
        chai.request(app)
            .get('/auth/logout')
            .end((err,res) => {
              expect(res.redirects[0]).to.match(/\/$/);
              // If @R_675_6048@sful layout displays Login links
              expect(res.text).to.match(/Login/);
              done();
            });
      });
  });

});@H_801_7@ 
 

完整源代码https://github.com/stujo/node-express-gamebase

大佬总结

以上是大佬教程为你收集整理的node.js – 使用Mocha和Chai测试Express和Passport OAuth2全部内容,希望文章能够帮你解决node.js – 使用Mocha和Chai测试Express和Passport OAuth2所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。