【问题标题】:api-easy - vows - setting cookie issueapi-easy - 誓言 - 设置 cookie 问题
【发布时间】:2015-02-18 19:50:56
【问题描述】:

我将api-easyvows 一起用于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);

知道如何让它运行吗?

【问题讨论】:

    标签: node.js angularjs unit-testing


    【解决方案1】:

    试试这个

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多