2016-05-10 10 views
0

私はJavascriptでテストし、mochaとchaiを使ってNodeJSバックエンドをテストしようとする初心者です。私のルートの全ては、それらがログインしていない場合は、人々が前進することはできませんミ​​ドルウェアで満たされている方法 。テストを実行する前に毎回ログインする方法

checkauth

var checkauth = function(req, res, next) { 
    console.log("In checkauth"); 
    if (req.isAuthenticated()) { 
     next(); 
    } else { 
     console.log("Doesn't authenticate"); 
     res.status(401); 
     res.set('Content-Type', 'application/json'); 
     res.end(JSON.stringify({ 
      'success': false 
     })); 
    } 
}; 
あるこの

app.post('/user/analytics/driverdata', checkauth, function(req, res) { 
     analytics.driverData(req, res); 
}); 

ような何か

isAuthenticatedパラメーターは、要求をデシリアライズするときにPassportJSによって要求に付加されます。 私がしたいのは、

app.post('/user/analytics/driverdata', checkauth, function(req, res) { 
      analytics.driverData(req, res); 
}); 

このAPIのテストを書くことです。私はそこに到達できないのでログインしていないので失敗している。 私はbeforeEachを書いてユーザbeforeEach itにログインしました。こんなふうになります。

var expect = require('chai').expect; 
var request = require('superagent'); 

beforeEach(function(done){ 
     //login into the system 
     request 
     .post("http:localhost:5223/user/authenticate/login") 
     .send({username : "[email protected]", password : "saras"}) 
     .end(function assert(err, res){ 
     if(err){ 
      console.log(err); 
      done(); 
     } 
     else{ 
      done(); 
     } 
    }); 
}); 

私は私が間違っているのかわからないし、インターネットは私を失敗しました。どこに間違っているのかを指摘する助けに感謝します。

答えて

0

私は最終的にそれをクラックしたと思います。エージェントのコンセプトに私をもたらしたthe answer hereは言うまでもありません。それは私がこれを打ち砕くのを助けた。 あなたの記述ブロック内、またはブロックの前におそらく次のようなものがありますit

var superagent = require('superagent'); 
var agent = superagent.agent(); 
it('should create a user session successfully', function(done) { 
     agent 
     .post('http://localhost:5223/user/authenticate/login') 
     .send({ 
       username: '[email protected]', 
       password: 'ssh-its-a-secret' 
     }) 
     .end(function(err, res) { 
      console.log(res.statusCode); 
      if (expect(res.statusCode).to.equal(200)) 
       return done(); 
      else { 
       return done(new Error("The login is not happening")); 
        } 
       }); 
     }); 

エージェントの変数は、ユーザーを認証するためにPassportJSで使用されているあなたのためにクッキーを、保持しています。

ここはあなたのやり方です。したがってエージェント変数はdescribeの内部にあります。同じでdescribe内に別のit

it("should test analytics controller", function(done) { 
agent.post('http://localhost:5040/user/analytics/driverData') 
     .send({ 
      startDate: "", 
      endDate: "", 
      driverId: "" 
     }) 
     .end(function(err, res) { 
      if(!err) 
      done(); 
     }); 
}); 

この機能は魅力的なものです。これは欠けていた完全なドキュメントの1つでした。

関連する問題