2014-03-25 71 views
1

我正在使用api-easyvowsAPI testing。我的一個API需要通過身份驗證的登錄才能訪問數據列表。api-easy - 誓言 - 設置cookie問題

所以第一我做了登錄/api/session & extacted 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

試試這個

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

我刪除了餅乾變量和使用的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);