2016-05-09 46 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(); 
        }); 
      }); 
    }); 
});