2016-09-21 32 views
1

我試圖在摩卡中測試驗證路線,但在beforebeforeEach掛鉤中創建的用戶不會持續存在。使用摩卡+ supertest +護照測試通過智威湯遜驗證的路線失敗

test.js

const should = require('chai').should(), 
    mongoose = require('mongoose'), 
    request = require('supertest'), 
    app = require('../../../../server'), 
    agent = request.agent(app), 
    AdminUser = require('../../../models/AdminUser'); 

var credentials = { 
    username: 'admin', 
    password: 'password' 
}; 

var admin = new AdminUser(credentials); 

describe('authenticated routes', function() { 
    before(function (done) { 
     admin.save(function (err) { 
      if (err) done(err); 

      agent.post('/api/authenticate') 
      .send(credentials) 
      .end(function (err, res) { 
       if (err) done(err); 
       jwtToken = res.body.token; 
       done(); 
      }); 
     }); 
    }); 

    it('should get content with 200', function (done) { 
     agent.get('/api/content') 
     .set('Authorization', 'JWT ' + jwtToken) 
     .expect(200) 
     .end((err, res) => { 
      if (err) return done(err); 
      done(); 
     }); 
    }); 

    after(function (done) { 
     AdminUser.remove().exec(); 
     done(); 
    }) 
}); 

我一直在使用beforeEachafterEach清理嘗試,最初的帖子/api/authenticate返回200成功,令牌被接收,但試圖與令牌身份驗證時,它得到一個400。這是由於找不到AdminUser

在護照的策略,我有:

module.exports = function (passport) { 
    passport.use(new JwtStrategy(opts, function(jwtPayload, done) { 
     AdminUser.findOne({ username: jwtPayload.username }, function (err, user) { 
      if (err) { return done(err); } 
      if (!user) { 
       return done(null, false, { message: 'Bad token.' }); 
      } 
      return done(null, user); 
     }); 
    })); 
}; 

AdminUser總是null無論在哪裏,我保存用戶。只適用於嵌套回調但是否定使用beforebeforeEach

回答

0

您需要使用Authorization頭與承載認證方案:

.set('Authorization', 'Bearer ' + jwtToken) 
相關問題