使用 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" 键上的 headers 值发送到服务器,因此您只需手动设置它们。
它适用于我的 mocha 和 chai-http,而且我能够在我的 koajs v2 应用程序中接收 cookie 值
为了补充 Pedro 的回答,我需要将会话 ID 设置到 cookie 中。为此,我在内部对象上使用 stringify 并使用 "cookieName=".
生成了 cookie 数据
const cValue = "cookieName=" + JSON.stringify({sessionId: sessionId});
chai.request(url)
.get("/userData")
.set('Cookie', cValue);
.then(...)
考虑以下代码:
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" 键上的 headers 值发送到服务器,因此您只需手动设置它们。
它适用于我的 mocha 和 chai-http,而且我能够在我的 koajs v2 应用程序中接收 cookie 值
为了补充 Pedro 的回答,我需要将会话 ID 设置到 cookie 中。为此,我在内部对象上使用 stringify 并使用 "cookieName=".
生成了 cookie 数据const cValue = "cookieName=" + JSON.stringify({sessionId: sessionId});
chai.request(url)
.get("/userData")
.set('Cookie', cValue);
.then(...)