lundi 28 septembre 2015

Unit Testing login token

I am working on adding unit testing to my application framework and everything is going well. I however have run into an issue testing if the token has expired or is still active.

I was able to test if the user token was created by mocking the response for my /login call with a token I saved for a test user, however this only works until the token expires. I have no way to manually expire the token or reset the expiration time to the future.

My auth factory:

auth.isLoggedIn = function(){
    var token = SS.getObj('appToken');
    if(token){
        var payload = JSON.parse($window.atob(token.split('.')[1]));
        return payload.exp > Date.now() / 1000;
    } else {
        return false;
    }
};

And my unit tests:

describe('auth.isLoggedIn()', function () {
    it('should return false if a user is not logged in', function () {
      expect(auth.isLoggedIn()).toEqual(false); // This test passes 100%
    });

    it('should return true if a user is logged in', function () {
      user = {
        email: 'bwayne@wayneenterprise.com',
        password: 'password123'
      };
      $httpBackend.expectPOST('/login').respond({ token: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6NywiZW1haWwiOiJid2F5bmVAd2F5bmVlbnRlcnByaXNlLmNvbSIsIm5hbWUiOiJCcnVjZSBXYXluZSIsImV4cCI6MTQzODI4NDYwNywiaWF0IjoxNDM4MjgxMDA3fQ.2rpGJ1c5dVi1EiPo0C5JIdva7MonutCYmotP5-pB_N4' }); // I copied a valid token from a test user, but I can't change it since I'm just copying an old token.
      auth.login(user);
      $httpBackend.flush();
      expect(auth.isLoggedIn()).toEqual(true); // This test passes if the above token has a valid time/date, however I can't set the time/date so it usually fails
    });

    it('should return false if a users token has expired', function () {
      user = {
        email: 'bwayne@wayneenterprise.com',
        password: 'password123'
      };
      $httpBackend.expectPOST('/login').respond({ token: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6NywiZW1haWwiOiJid2F5bmVAd2F5bmVlbnRlcnByaXNlLmNvbSIsIm5hbWUiOiJCcnVjZSBXYXluZSIsImV4cCI6MTQzODI4NDYwNywiaWF0IjoxNDM4MjgxMDA3fQ.2rpGJ1c5dVi1EiPo0C5JIdva7MonutCYmotP5-pB_N4' });
      auth.login(user);
      $httpBackend.flush();
      expect(auth.isLoggedIn()).toEqual(false); // This test fails if the date/time has expired, again I can't set that so it's usually passing, as the token has expired.
    });
  });

I suspect the proper way to do this is to actually create a valid token during the test, but I'm not sure how to do that as it's handled by the node server who's responses I mock to avoid relying on a server response in my tests.

Aucun commentaire:

Enregistrer un commentaire