Search code examples
node.jsmocha.jschaichai-http

What is the proper way to test routes secured with jwt token?


While the following test passes I feel I'm doing this wrong. Am I expected to log in every time i need to test a secure route? I've tried passing global vars around after i get the initial token but passing vars i'm finding extremely counter intuitive. Passing variables in a before() call presents me same issue as passing / accessing global vars inside nested promises.

describe('Users', function(done) {
  var testToken = 'my-test-token'
  it('logs in', function(done) { // <= Pass in done callback
    var rT = 'tttttt'
    chai.request(urlroot)
      .post('/login')
      .type('form')
      .send({ email: '[email protected]', password: '9999' })
      .end(function(err, res) {
        expect(res).to.have.status(200);
        expect(res.body.token).to.be.a('string');
        done()
      });
  });

  it('gets all users', function(done) { // <= Pass in done callback
    // console.log(urlroot + '/users');
    chai.request(urlroot)
      .post('/login')
      .type('form')
      .send({ email: '[email protected]', password: '9999' })
      .end(function(err, res) {
        chai.request(urlapi)
          .get('/users?secret_token='+res.body.token)
          .end(function(err, res){
            console.log('data', res.body);
            // expect(res.body).to.be.json()
          })
      });
  });
});

Solution

  • What I do is use before() method to call my authenticate service to get the token in the same way that the aplication would, and store into a variable.

    Something like:

    var token = "";
    before(async () => {
        //Get token
        token = "Bearer " + await getToken();
    });
    

    Then, in every test you want to use the credentials use .set()

    it('...', function (done) {
        chai
          .request(url)
          .set("Authorization", token) //Call .set() before .get()
          .get("/users")
          //...
    })