我正在api-easy
使用vows
API testing
。我的一个api需要经过身份验证的登录才能访问数据列表。
所以我第一次登录/api/session
&推出了cookie&在我的第二次api通话中使用它。但它仍然给我错误 - unauthorised
。
var cookies;
suite.discuss('When using your awesome API')
.use('localhost', 9000)
.setHeader('Content-Type', 'application/json; charset=utf-8')
.post('/api/session', {'username': 'siteadmin', 'password': 'siteadmin' })
.expect(200)
.expect('should login', function (err, res, body) {
res.headers['set-cookie'].filter(function (cookie) {
if (!!~cookie.indexOf('connect.sid')) {
cookies = cookie.split(';', 1)[0];
}
})
})
.next()
.discuss('and your awesome resource')
.use('localhost', 9000)
.setHeader('Content-Type', 'application/json; charset=utf-8')
.setHeader('Cookie', cookies)
.get('/api/list/name')
.expect(200)
.export(module);
知道如何让它运行吗?
答案 0 :(得分:0)
试试这个
suite.discuss('When using your awesome API')
.use('localhost', 9000)
.setHeader('Content-Type', 'application/json; charset=utf-8')
.post('/api/session', {'username': 'siteadmin', 'password': 'siteadmin' })
.expect(200)
.expect('should login', function (err, res, body) {
assert.include(res.headers, 'set-cookie');
suite.before('setAuth', function (outgoing) {
outgoing.headers['Cookie'] = res.headers['set-cookie'][0];
return outgoing;
});
})
.next()
.discuss('and your awesome resource')
.use('localhost', 9000)
.setHeader('Content-Type', 'application/json; charset=utf-8')
.get('/api/list/name')
.expect(200)
.export(module);
我删除了cookies变量,并使用suite.before方法将cookie注入标题。
从定义suite.before函数的那一刻起,cookie将在套件中的所有顺序请求中设置。因此,您可以在两个测试中拆分上述示例:
suite.discuss('When using your awesome API')
.use('localhost', 9000)
.setHeader('Content-Type', 'application/json; charset=utf-8');
suite.discuss('and sending login data to')
.post('/api/session', {'username': 'siteadmin', 'password': 'siteadmin' })
.expect(200)
.expect('should login', function (err, res, body) {
assert.include(res.headers, 'set-cookie');
suite.before('setAuth', function (outgoing) {
outgoing.headers['Cookie'] = res.headers['set-cookie'][0];
return outgoing;
});
});
suite.discuss('then after login')
.get('/api/list/name')
.expect(200);
suite.export(module);