繁体   English   中英

使用chai在请求上设置cookie

[英]Setting a cookie on the request with chai

考虑以下代码:

    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来绕过一个启动页面。 有关如何实现这一目标的任何想法?

这应该工作:

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM