2016-05-09 47 views
0

我最近在學習如何編寫摩卡和超級測試。 當我嘗試測試一個帖子url時,它需要_csrf屬性,所以我檢查這個 [如何用CSRF測試快遞單發佈?摩卡測試錯誤CSRF令牌不匹配

] 1

和把下面的代碼

var request = require('supertest'); 
var should = require('should'); 
var app = require('../app'); 
var $ = require('jquery')(require("jsdom").jsdom().parentWindow); 


describe('User', function() { 

    it('should create a admin', function (done) { 
     request(app) 
      .get('/rear') 
      .expect(200) 
      .end(function (err, res) { 
       if (err) return done(err); 
       should.not.exist(err); 
       var $html = $(res.text); 
       var csrf = $html.find('input[name=_csrf]').val(); 
       console.log(csrf); 
       should.exist(csrf); 
       request(app) 
        .post('/user/signup') 
        .send({ 
         _csrf: csrf, 
         name: 'admin', 
         mobile: '12345678901', 
         password: '123456', 
         repassword: '123456', 
         gender: '0' 
        }) 
        .expect(302) 
        .end(function (err, res) { 
         if (err) return done(err); 
         should.not.exist(err); 
         res.header.location.should.include('/rear'); 
         done(); 
        }); 
      }); 
    }); 
}); 

終端通知, 錯誤:CSRF令牌不匹配 錯誤:預期302 「找到」,得到了403 「禁止」

我的代碼模仿用戶行爲,在/後路由器渲染的頁面上獲取csrf,然後將它和其他信息發佈到/ user/signup,我不知道錯在哪裏以及如何修復它。如果您發現原因,請提醒我,非常感謝。

回答

0

我找出麻煩的地方。我得到了csrf中間件lusca公開的表單服務器到輸入中的首頁(name ='_ csrf'),但我忽略了它在測試env時也應該堅持一個請求及其cookie,我再次檢查supertest doc發現它可以調用。代理方法來實現它。

var agent = request.agent(app); 

describe('User', function() { 

    it('should create a admin', function (done) { 
     agent 
      .get('/rear') 
      .expect(200) 
      .end(function (err, res) { 
       if (err) return done(err); 
       should.not.exist(err); 
       var $html = $(res.text); 
       var csrf = $html.find('input[name=_csrf]').val(); 
       console.log(csrf); 
       should.exist(csrf); 
       request(app) 
        .post('/user/signup') 
        .send({ 
         _csrf: csrf, 
         name: 'admin', 
         mobile: '12345678901', 
         password: '123456', 
         repassword: '123456', 
         gender: '0' 
        }) 
        .expect(302) 
        .end(function (err, res) { 
         if (err) return done(err); 
         should.not.exist(err); 
         res.header.location.should.include('/rear'); 
         done(); 
        }); 
      }); 
    }); 
});