为什么在测试时我的处理函数中没有我的cookie?

时间:2016-10-06 16:49:36

标签: node.js testing hapijs

我正在使用Hapi,这是我的处理函数:

function propertyDetailsValidateHandler(request, reply, source, error) {
console.log(request.state)  
var data = joiValidationHelper.checkForErrors(request, error);
  if (typeof data !== "undefined"){
    return reply.view('property-details', data).code(400);
  } else {
    var details = request.state.details;
    details.propertyType = request.payload.propertyType;
    details.newBuild = request.payload.newBuild;
    return reply.redirect('/property-details/postcode').state('details', details, {path: '/'});
  }
}

这是我用Jasmine编写的测试:

describe('tell us about the property youre buying flow', function(){
  it('test /property-details, status code and location', function(done){
    var options = {
      method: 'POST',
      url: '/property-details',
      headers: {
        cookie: {details: { test: "test"}}
      },
      payload: {
        propertyType: "freehold",
        newBuild: true
      }
    };
    server.inject(options, function(response){
      detailsTestCookie = response.headers['set-cookie'][0].split(';')[0];
      expect(response.statusCode).toBe(302);
      expect(response.headers.location).toMatch("/property-details/postcode");
      done();
    });
  });
})

当我运行我的服务器并使用浏览器时,处理程序函数正确运行,但是当我运行测试request.state是一个空对象,当我期望它是我在测试中提供的cookie时因此我的测试失败作为请求.state.details未定义。这是在我的测试中为标题提供cookie的正确方法吗?

2 个答案:

答案 0 :(得分:2)

这适用于我们的项目,使用磁带和Hapi。

var cookie = the_cookie_you_want_to_send;

然后在你的测试有效载荷中:

headers: { cookie: `details=${cookie}`}

答案 1 :(得分:1)

需要对cookie进行编码,因为cookie是在我们的服务器文件中注册的方式:

server.state('details', {
  ttl: null,
  isSecure: false,
  isHttpOnly: false,
  encoding: 'base64json', //this is not encrypted just encoded
  clearInvalid: false, // remove invalid cookies
  strictHeader: false // don't allow violations of RFC 6265
});