簡體   English   中英

如何測試sail.js控制器,用戶使用passport.js登錄

[英]How to test sail.js controller with user logged in with passport.js

我嘗試對需要用戶登錄的sail.js控制器進行單元測試。我目前的測試是:

var request = require('supertest'),   // I try to use 'superagent', this changes nothing
    user = request.agent;

describe('SomeController', function() {
    // login user first of all
    before(function(done) {
        user(sails.hooks.http.app)
            .post('/user/login')
            .send({username: 'hellocat', password: '123456789'})
            // request works well by itself, 
            // it does not return error and return normal response.
            .end(function (err, res) {
                // then I try to save cookies of logged in user to it agent
                user(sails.hooks.http.app).saveCookies(res);
                done();
            });
    });

    // let test something
    it('must return "ok" when user is logged in or "wtf" if opposite', function(done) {
        user(sails.hooks.http.app)
            .get('/user/me')
            .end(function(err, res) {
                console.log(res.body);
                // no need to expect something, user is not logged in (
                done();
            });
    });

});

掛鈎工作正常之前我的用戶在請求結束時登錄。 但在測試中它不是。 在所有測試開始運行之前,我解除了sails應用程序。 不需要授權的類似測試工作得很好。 我猜這個錯誤可能是在保存cookie或錯誤理解如何使用超級代理。 我究竟做錯了什么?

好吧,我終於找到了我的錯誤。 request.agent函數不返回singleton。 因此, user(sails.hooks.http.app)每次調用user(sails.hooks.http.app)實際上都是新代理和新用戶。 為了使這個測試片段工作,我應該做這樣的事情

var request = require('supertest'),
    agent = request.agent;

並在描述部分調用代理:

describe('SomeController', function() {

    var user;

    before(function(done) {
        user = agent(sails.hooks.http.app);
        user
            .post('/user/login')
            // ...
    // ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM