Supertest, test secure REST API

前端 未结 2 830
失恋的感觉
失恋的感觉 2021-01-31 21:19

I am writing an integration test for a REST API protected by a jwt. One API operation POST /user/token is returning a jwt given a us

相关标签:
2条回答
  • 2021-01-31 21:47

    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);
      });
    });
    
    0 讨论(0)
  • 2021-01-31 21:47

    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);
      });
    
    0 讨论(0)
提交回复
热议问题