Question

Je voudrais de l'unité de test d'une directive qui redirige l'utilisateur vers le social login-url à la sauvegarde.

depuis le Karma ne prend pas en charge complète de la page recharge, je voudrais modifier le comportement de l'emplacement.href objet JavaScript pour la sortie du paramètre qu'il reçoit à un élément HTML avec une certaine ID, et je vais avoir des difficultés à le faire.

directive:

__app.directive('socialAuth', function(utils, authService, $location){
    return{
            restrict: 'A',
            scope: false,
            link: function(scope, elem, attrs){
                elem.bind('click', function(){
                            utils.cleanSocialSearch();
                            if(attrs.checkbox == 'personal'){
                              scope.$apply(function(){
                                scope.model.personalShare[attrs.network] = true;  
                                $location.search('personalShare', '1');
                              });
                            }
                            else if(attrs.checkbox == 'group'){
                              scope.$apply(function(){
                                var __index = attrs.checkbox + '_' + attrs.network;
                                scope.model.personalShare[__index] = true;  
                                $location.search('groupShare', '1');
                              });
                            }
                              var callback = encodeURIComponent(window.location.href);
                              var loginUrl = utils.getBaseUrl() + '/social/login/' + attrs.network + '?success_url=' + callback;
                              location.href = loginUrl;  

                        });
            }
    }

});

Test avec une tentative de se moquer de l'emplacement.href objet(ouais, je sais c'est pas une fonction):

var location = {//an attempt to mock the location href object
  href: function(param){
    $('#content').html(param);
  }
};

'use strict';
    describe('socail-auth', function(){//FB
      var scope, compiled, linkFn, html, elem, elemPersonal, elemGroups, compile, authService;
      html = "<span id='content' data-social-auth data-network='facebook'>";
      beforeEach(function(){
        module('myApp.directives');
        module('myApp.services');

    inject(function($compile, $rootScope){
      scope = $rootScope.$new();
      linkFn = $compile(angular.element(html));
      elem = linkFn(scope);
      scope.$digest();
      elem.scope().$apply()
    });
 })
    it("should redirect user to social login url at the backend", function(){
      // console.log(location.href);
      elem.click();
      console.log($(elem).html());
      expect($(elem).html()).toBeDefined();

    });

});
Était-ce utile?

La solution 2

La solution consiste à envelopper la redirection à l'API dans une fonction de service et à vous moquer de l'URL du test pour enregistrer l'URL de redirection dans une variable de service, puis l'exposer à une méthode getter au test au lieu de redirigerça.

Un module peut être fait à partir de l'organisme de test:

module('myApp.services.mock', function($provide){
  var __service = function(){
     var __data;
     return{
        getFn: function(){
          return __data;
        },
        setFn: function: function(data){
          __data = data;
        }
     }
  }
  $provide.value('someService', __service);
});

mais j'ai choisi de séparer cette intro de ce modèle de propre modèle afin d'améliorer la structure et la modularité

'use strict';
angular.module('myApp.services.mock', ['urlConfig']).
    factory('utils', function(API_URL, $location, $rootScope, $window){
        var __redirectURL = $window.location.href;
        var utilsMock = {
          getBaseUrl: function(){
              return API_URL;
          },
          getLocationHref: function(){
              return __redirectURL;
          },
          setLocationHref: function(redirectURL){
            $rootScope.$apply(function(){
                __redirectURL = redirectURL;
            });

          },
          cleanSocialSearch: function(){
              $location.search('auth_success', null);
              $location.search('auth_error', null);
              $location.search('auth_media', null);
              $location.search('personalShare', null);
              $location.search('groupShare', null);
          }
        }
        return utilsMock;
    });

-

__app.directive('socialAuth', function(utils, $location){
    return{
            restrict: 'A',
            scope: false,
            link: function(scope, elem, attrs){
                elem.bind('click', function(){
                            utils.cleanSocialSearch();
                            if(attrs.checkbox == 'personal'){
                              scope.$apply(function(){
                                scope.model.personalShare[attrs.network] = true;  
                                $location.search('personalShare', '1');
                              });
                            }
                            else if(attrs.checkbox == 'group'){
                              scope.$apply(function(){
                                var __index = attrs.checkbox + '_' + attrs.network;
                                scope.model.personalShare[__index] = true;  
                                $location.search('groupShare', '1');
                              });
                            }
                              var callback = encodeURIComponent(utils.getLocationHref());
                              var loginUrl = utils.getBaseUrl() + '/social/login/' + attrs.network + '?success_url=' + callback;
                              utils.setLocationHref(loginUrl);  

                        });
            }
    }

});

et enfin le test:

describe('socail-auth', function(){//FB
  var scope, compiled, linkFn, utils, html, elem, elemPersonal, elemGroups, compile, authService, utilsMock, _window, BASE_URL, __network;
  __network = 'facebook';
  html = "<span data-social-auth data-network='" + __network + "'></span>";

  beforeEach(function(){
    module('urlConfig');
    module('myApp.services.mock');
    module('myApp.directives');
    inject(function($compile, $rootScope, $injector){
      scope = $rootScope.$new();
      utils = $injector.get('utils');
      _window = $injector.get('$window');
      BASE_URL = $injector.get('API_URL');
      linkFn = $compile(angular.element(html));
      elem = linkFn(scope);
      // scope.$digest();
      elem.scope().$apply()  
    });
 })
    it("should redirect user to social login url at the backend", function(){
      elem.click();
      //scope.$digest();
      var loginUrl = BASE_URL + '/social/login/' + __network + '?success_url=' + encodeURIComponent(_window.location.href);


       expect(utils.getLocationHref()).toEqual(loginUrl);


   });
 });

Autres conseils

Utilisation $window.location.href au lieu de location.href.

Ensuite se moquer de $window.location avec un objet vide, il va faire le travail.

describe('location', function() {
    var $window;

    beforeEach( module('myApp') );

    // You can copy/past this beforeEach
    beforeEach( module( function($provide) {

        $window = { 
            // now, $window.location.path will update that empty object
            location: {}, 
            // we keep the reference to window.document
            document: window.document
        };

        // We register our new $window instead of the old
        $provide.constant( '$window' , $window );
    }))


    // whatever you want to test
    it('should be redirected', function() {

        // action which reload the page
        $scope.reloadPage();

        // we can test if the new path is correct.
        expect( $window.location.path ).toBe('/the-url-expected');

    })
})
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top