How to validate defaultPrevented = false in my Angularjs test?

Asked

Viewed 58 times

0

I have the following function:

(function () {
'use strict';

angular.module("app")

.service('EventHandler', EventHandler);

EventHandler.$inject = ['$rootScope', '$location', '$animate', '$state', '$stateParams', '$sanitize', '$q', '$uibModal', 'toastr',
'storage', 'StorageService', 'LogService', 'LanguageResource', 'LoginService', 'StcpUtilsService', 'DAOService',
'CSRF', 'Authorization', 'ShortcutService', 'data_login', 'PermissionsService', 'BusinessLogicService', 'DebugMode'
]; 

function EventHandler($rootScope, $location, $animate, $state, $stateParams, $sanitize, $q, $uibModal, toastr, storage, StorageService,
                  LogService, LanguageResource, LoginService, StcpUtilsService, DAOService, CSRF,
                  Authorization, ShortcutService, data_login, PermissionsService, BusinessLogicService, Debug) {

var animate;
/* = parameters.$animate || $animate; */
var rootScope;
/* = parameters.$rootScope || $rootScope; */
var scope;
/* = parameters.$scope; */
var _toastr;
/* = parameters.toastr || toastr; */
var _storage;
/* = parameters.StorageService || StorageService; */
var location;
/* = parameters.$location || $location; */
var log;
/* = parameters.LogService ? parameters.LogService.log : LogService.log || LogService.log; */
var language;
/* = parameters.LanguageResource || LanguageResource; */
var shortcut;
var t;
var dao;
var DebugMode;

return {
    initialize: initialize_component,
    onCheckSession: onCheckSessionHandle,
    onLogin: onLoginHandle,
    onLogout: onLogoutHandle,
    onStateChangeError: onStateChangeErrorHandle,
    onHideMenuCheck: onHideMenuCheckHandle,
    onSetInstance: onSetInstanceHandle,
    onRemoveInstance: onRemoveInstanceHandle,
    onGetInstanceName: onGetInstanceNameHandle,
    onGetInstanceId: onGetInstanceIdHandle,
    onGetOperatorLogged: onGetOperatorLoggedHandle,
    onOperatorIsLogged: onOperatorIsLoggedHandle,
    onShakeMenu: onShakeMenuHandle,
    onCheckInstance: onCheckInstanceHandle,
    onSave: onSaveHandle,
    onDelete: onDeleteHandle,
    onInterceptError: onInterceptErrorHandle,
    onChangeOperatorPassword: onChangePasswordHandle,
    onGetTransfer: onGetTransferHandle,
    onOpenChangeModuleDialog: onOpenChangeModuleDialogHandle,
    onChangeSubModule: onChangeSubModuleHandle,
    onDisplaySelectionInstance: onDisplaySelectionInstanceHandle,
    onGetInstances: onGetInstancesHandle,
    onCheckModule: onCheckModuleHandle,
    // onDataToPersist: onDataToPersistHandle
};

// function onDataToPersistHandle() { rootScope.$on('dataToPersist', onDataToPersist); }

function onRemoveInstanceHandle() {
    rootScope.$on('removeInstance', onRemoveInstance);
}        

function onCheckSessionHandle() {
        rootScope.$on('checkSession', onCheckSession);
}

function onRemoveInstance(ev, args) {
    onCheckSession(ev, args);

    if (ev.defaultPrevented === false) {
        _storage[storage].del("instance_id");
        _storage[storage].del("instance_name");
        _storage.local.del("instance_name");
        _storage.local.del("instanceSelected");
        _storage.session.del("instanceSelected");
        rootScope.instanceSelected = undefined;
        delete rootScope.displaySelectionInstance;
        delete rootScope.instance_id;
        delete rootScope.instance_name;
    }
} 

  function onCheckSession(ev, args) {
        var serv;
        var opLogged;
        var head_req;
        var perm;
        var userLog;
        var token;
        var current_module;

        try {
            serv = StorageService[storage];
        } catch (e) {
            console.error(e.message);
        }
        try {
            opLogged = serv.get('operator_logged') || null;
        } catch (e) {
            opLogged = null;
        }
        try {
            head_req = serv.get('header_request') || null;
        } catch (e) {
            head_req = null;
        }
        try {
            perm = serv.get('permissions') || null;
        } catch (e) {
            perm = null;
        }
        try {
            userLog = serv.get('userLogged') || null;
        } catch (e) {
            userLog = null;
        }
        try {
            token = serv.get('token_info') || null;
        } catch (e) {
            token = null;
        }
        try {
            current_module = serv.get('current_module');
        } catch (e) {
            current_module = null;
        }

        if (token === null || opLogged === null || head_req === null || perm === null || userLog === null) {
            if (LoginService.doLogout()) {
                // Previne que o listener passado por parâmetro seja executado.
                ev.preventDefault();
                // Previne que os demais listeners assinados ao evento passado sejam executados.
                ev.stopPropagation();
                // Retira do escopo raiz dados do operador logado.
                $rootScope.operator_logged = undefined;
                // Inibe a exibição do Menu principal.
                $rootScope.hideMenu = true;
                // Se não estiver no estado de login.
                Eif (!$state.is('login') && !$state.is('master.modules')) {
                    // Exibe mensagem de sessão expirada.
                    _toastr.warning(t('Sessão expirada, inicie uma nova sessão!'), t("Sessão expirada!"));
                    $state.go("login", {location: "replace"});
                } else if (!$state.is('login')) {
                    // Redireciona para o estado de login.
                    $state.go("login", {location: "replace"});
                }
            }
        }
    }

//...

And I’m applying the following test in order to validate Ev.defaultPrevented = false so you can enter if

  it('testing if the onRemoveInstance function', function(){ 
    var args;
    var ev = {
        defaultPrevented: false 
    };

    function onRemoveInstance(ev) {
        if (ev.defaultPrevented === false) {
            srv.onRemoveInstance();
            rootScope.$emit('removeInstance');
        }
    }
    onRemoveInstance(ev);

    Array.prototype.removeByAttr = srv.onCheckSession(ev, args);       
});   

But it’s not getting inside the if. I’d like to know what I’m doing wrong and what the right way for the test to work.

  • I believe onCheckSession is modifying the value of Ev

  • @Felipeduarte knows how to fix it?

  • 1

    just check the return of the function onCheckSession, and what causes this change, if you want to edit the code with the same

  • @Felipeduarte was edited

  • 1

    Good as I could see onCheckSession is referencing onCheckSessionHandle, I do not know if you have access to this function because your project is well modularized, remove onCheckSession(Ev, args); from the method onRemoveInstance, I believe you will enter the if, ai just tidy onCheckSession later.

  • @Felipeduarte knows how to remove this onCheckSession within my test iteration?

  • 1

    I’ll try to answer but your problem is not something easy to understand

Show 2 more comments

1 answer

1

Default prevented was defined here (remembering that this event only works effectively on object DOM)

srv.ev = {
            defaultPrevented: false   
        }

By calling onRemoveInstance, onCheckSession is modifying ev, therefore ev.defaultPrevented will no longer be false.

function onRemoveInstance(ev, args) {
    onCheckSession(ev, args); <--------

    if (ev.defaultPrevented === false) {
        _storage[storage].del("instance_id");
        _storage[storage].del("instance_name");
        _storage.local.del("instance_name");
        _storage.local.del("instanceSelected");
        _storage.session.del("instanceSelected");
        rootScope.instanceSelected = undefined;
        delete rootScope.displaySelectionInstance;
        delete rootScope.instance_id;
        delete rootScope.instance_name;
    }
} 

In a simple example

var ev = {
  defaultPrevented: false 
};

function onRemoveInstance(ev) {
  if (ev.defaultPrevented === false) {
   alert('entrou');
  }
}

onRemoveInstance(ev);

  • I understood what you meant. Regarding my test what you were doing will be useless in trying to get into the if. Could I do inside my test a mock of an instance to remove that onCheckSession that is modifying my function? And how to do this ?

  • 1

    defaultPrevented checks whether an element in the gift is in the right preventive state? in the function onCheckSession there is an if with the following Ev.preventDefault(); ie to be giving false, it was necessary to enter that if, there is the root of the problem, do not know how it entered, because it is not a DOM object, but I don’t know how it works because I’ve never done preventive tests, so that you don’t enter if, Ev.preventDefault(); it can’t be set

Browser other questions tagged

You are not signed in. Login or sign up in order to post.