【问题标题】:Setting a cookie on the request with chai使用 chai 在请求上设置 cookie
【发布时间】:2016-06-27 11:02:10
【问题描述】:

考虑以下代码:

    it('Test logout', function (done) {
    async.each(config.www, function (url, callback) {
        var healthCheck = url + '/'
        chai.request(url).get('/')
            .then(function (res) {
                expect(res, healthCheck).to.have.status(200);
                expect(res.text.indexOf(url + '/logout?type=user">Log out</a>'), 'Logout is incorrect').to.be.greaterThan(0);
                callback();
            })
            .catch(function (err) {
                callback(err);
            })
    }, done);
});

问题是我需要设置一个 cookie 来绕过启动页面。 关于如何实现这一目标的任何想法?

【问题讨论】:

  • 不太清楚如何将其添加到请求中。
  • 嗨,没试过,但我猜你必须在请求之前创建 cookie 作为测试设置的一部分?

标签: javascript cookies chai


【解决方案1】:

这应该可行:

chai.request(url)
    .get('/')
    .set('Cookie', 'cookieName=cookieValue;otherName=otherValue')
    .then(...)

Cookies 作为“Cookie”键上的标头值发送到服务器,因此您只需手动设置它们。

它适用于 mocha 和 chai-http,我能够在我的 koajs v2 应用程序中接收 cookie 值

【讨论】:

    【解决方案2】:

    为了增加 Pedro 的回答,我需要将会话 ID 设置到 cookie 中。为此,我在内部对象上使用 stringify 并使用“cookieName =”生成 cookie 数据。

    const cValue = "cookieName=" + JSON.stringify({sessionId: sessionId});
    chai.request(url)
        .get("/userData")
        .set('Cookie', cValue);
        .then(...)
    

    【讨论】:

      猜你喜欢
      • 2014-02-08
      • 2016-07-21
      • 2016-06-01
      • 2021-07-01
      • 2014-10-19
      • 2017-08-05
      • 1970-01-01
      • 1970-01-01
      • 2017-12-04
      相关资源
      最近更新 更多