我正在使用frisby来自动化REST API测试。我的所有REST API都基于json并返回json响应。在其中一个要求中,我需要读取响应头并获取响应头并将其设置为下一个请求。使用json响应,我无法读取响应头。以下是我测试的示例代码。
frisby.create("Check to make sure that user does exist")
.get(hostURL + "/api/users/checkusername/" + username, user, {json: true}, {headers: {'Content-Type': 'application/json'}})
.expectHeaderContains('content-type', 'application/json')
.afterJSON(function (response) {
//How to read session id from header
//var sessionId = res.headers[constants.SESSION_ID_HEADER_KEY];
var exist = response.exist;
expect(exist).toBe(true);
});
请帮忙。
答案 0 :(得分:1)
您的代码实际上没问题,您只是尝试使用' res'变量而不是响应。
frisby.create("Check to make sure that user does exist")
.get(hostURL + "/api/users/checkusername/" + username, user, {json: true}, {headers: {'Content-Type': 'application/json'}})
.expectHeaderContains('content-type', 'application/json')
.afterJSON(function (response) {
var sessionId = response.headers[constants.SESSION_ID_HEADER_KEY];
// Use the sessionId in other frisby.create(...) call
}).
toss();
另一种方法是使用after(),如下所示:
frisby.create("Check to make sure that user does exist")
.get(hostURL + "/api/users/checkusername/" + username, user, {json: true}, {headers: {'Content-Type': 'application/json'}})
.expectHeaderContains('content-type', 'application/json')
.after(function (err, res, body) {
var obj = JSON.parse(body);
var sessionId = obj.headers[constants.SESSION_ID_HEADER_KEY];
// Use the sessionId in other frisby.create(...) call
}).
toss();