admin管理员组

文章数量:1207122

Consider following code:

    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);
});

The problem is that I need to set a cookie to bypass a splash-page. Any ideas on how I can achieve this?

Consider following code:

    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);
});

The problem is that I need to set a cookie to bypass a splash-page. Any ideas on how I can achieve this?

Share Improve this question asked Jun 27, 2016 at 11:02 HomewreckerHomewrecker 1,1061 gold badge16 silver badges39 bronze badges 3
  • does this help ? stackoverflow.com/questions/6456429/… – bfmags Commented Jun 27, 2016 at 11:19
  • not quite sure on how to add it to the request. – Homewrecker Commented Jun 27, 2016 at 12:59
  • Hi, haven't tried it, but I'm guessing you have to create the cookie before the request as part of the setup for the test ? – bfmags Commented Jun 27, 2016 at 14:15
Add a comment  | 

2 Answers 2

Reset to default 21

This should work:

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

Cookies are send to the server as headers value on "Cookie" key, so you just have set them manually.

It works for me with mocha and chai-http, and i was able to recive the cookie values in my koajs v2 app

To augment Pedro's answer I needed to set the session ID into the cookie. To do this I generated the cookie data with stringify on the inner object and using "cookieName=".

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

本文标签: javascriptSetting a cookie on the request with chaiStack Overflow