Super test, test secure REST API

筅森魡賤 提交于 2019-12-03 09:45:37

问题


I am writing integration test for a REST API protected by a jwt. One API operation POST /user/token is returning a jwt given a username and a password and this token is then used for a list of operations such as:

GET /user/:id

Where the route is using jwt({secret: secret.secretToken}), so the token is included into the http header Authorization.

When testing with super test, I can have nested testing but I want to first get the token, then use this token for other operation testing.

POST /user/token => 12345
GET /user/:id, `Authorization Bearer 12345`
GET /user/:foo, `Authorization Bearer 12345`

How to avoid generating a new token for every operation testing (see below) but use only a single one generate by POST /user/token.

it('should get a valid token for user: user1', function(done) { 
  request(url)
    .post('/user/token')
    .send({ _id: user1._id, password: user1.password })
    .expect(200) // created
      .end(function(err, res) {
        // test operation GET /user/:id

回答1:


You want to perform single POST to /user/token and then use the token received in every test case? If so, then use the before hook of the test framework you are using (Mocha?) and store the token to a variable, e.g.

describe('My API tests', function() {

  var token = null;

  before(function(done) {
    request(url)
      .post('/user/token')
      .send({ _id: user1._id, password: user1.password })
      .end(function(err, res) {
        token = res.body.token; // Or something
        done();
      });
  });

  it('should get a valid token for user: user1', function(done) { 
    request('/get/user')
      .set('Authorization', 'Bearer ' + token)
      .expect(200, done);
  });
});



回答2:


Need to set Authorization as 'Bearer ' + token

 var token = null;

 before(function(done) {
    request(url)
      .post('/user/token')
      .send({ _id: user1._id, password: user1.password })
      .end(function(err, res) {
        token = res.body.token; // Or something
        done();
      });
  });


 it('should get a valid token for user: user1', function(done) { 
    request('/get/user')
      .set('Authorization', 'Bearer ' + token)
      .expect(200, done);
  });


来源:https://stackoverflow.com/questions/26453990/super-test-test-secure-rest-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!