Typeerror: Undefined is not an Object (evaluating 'self.data.ID')

Asked

Viewed 909 times

3

I’m trying to apply unit testing to my function onPersistSuccess, but this error appears

Typeerror: Undefined is not an Object (evaluating 'self.data.ID')

I have tried to define it in several ways but the error persists. I would like to know what the interference of this in calling this in test cases and how I can solve.

Below follows my function and test iterations:

(function () {
'use strict';

angular.module('app')
    .service('BusinessLogicService', BusinessLogicService);

BusinessLogicService.$inject = ['$rootScope', '$state', '$stateParams', 'StcpUtilsService', 'StorageService', 'storage', 'LanguageResource'];

function BusinessLogicService($rootScope, $state, $stateParams, StcpUtilsService, StorageService, storage, LanguageResource) {

    var self = this;
    var t = LanguageResource.t;
    var _storage = StorageService[storage];

    self.data = null;
    self.form = null;
    self.paramsRedirect = null;
    self.redirect = null;
    self.refresh = null;
    self.user_id = null;
    self.instance_id = null;

    function ruleInstances() {
        self.data.CONFIG_TXT.Startup.ServiceName = self.data.NAME;
        self.data.CONFIG_TXT.Startup.ServiceDescription = self.data.DESCRIPTION;

        return self.data;
    }

    function ruleUsers() {
        try {
            self.data.CONFIG_TXT.General.IdCodeProfile = self.data.NAME;
            self.data.CONFIG_TXT.General.Description = self.data.DESCRIPTION;

            // Se Protocolo OFTP
            if (self.data.CONFIG_TXT.General.TransferProtocol === 1) {
                self.data.CONFIG_TXT.Net1.TCPMaxRecvTO = self.data.CONFIG_TXT.Net2.TCPMaxRecvTO = self.data.CONFIG_TXT.OFTP.Timeout;
                self.data.CONFIG_TXT.Net1.TCPMaxSendTO = self.data.CONFIG_TXT.Net2.TCPMaxSendTO = self.data.CONFIG_TXT.OFTP.Timeout;
                // Se Protocolo SFTP
            } else if (self.data.CONFIG_TXT.General.TransferProtocol === 2) {
                self.data.CONFIG_TXT.Net1.TCPMaxRecvTO = self.data.CONFIG_TXT.Net2.TCPMaxRecvTO = self.data.CONFIG_TXT.SFTP.Timeout;
                self.data.CONFIG_TXT.Net1.TCPMaxSendTO = self.data.CONFIG_TXT.Net2.TCPMaxSendTO = self.data.CONFIG_TXT.SFTP.Timeout;
            } else { // Se Ambos OFTP e SFTP.
                var aux = self.data.CONFIG_TXT.OFTP.Timeout >= self.data.CONFIG_TXT.SFTP.Timeout ? self.data.CONFIG_TXT.OFTP.Timeout : self.data.CONFIG_TXT.SFTP.Timeout;
                self.data.CONFIG_TXT.Net1.TCPMaxSendTO = self.data.CONFIG_TXT.Net2.TCPMaxSendTO = aux;
            }

            if (self.form.Password.$pristine) {
                delete self.data.CONFIG_TXT.General.Password;
            }

            if (self.form.OdettePassword.$pristine) {
                delete self.data.CONFIG_TXT.OFTP.Password;
            }

            if (self.form.SFTPPassword.$pristine) {
                delete self.data.CONFIG_TXT.SFTP.Password;
            }
        } catch (ex) {
            console.log(ex.message);
        }

        return self.data;
    }

    function ruleServices() {//Services
        self.data.CONFIG_TXT.Service.Description = self.data.DESCRIPTION;

        // Seta TCPMaxRecvBuf e TCPMaxSendBuf
        // ServiceType = 0 == OFTP
        // ServiceType = 4 == Monitor.
        if (self.data.CONFIG_TXT.Service.ServiceType === 0) {
            self.data.CONFIG_TXT.Net1.TCPMaxRecvBuf = self.data.CONFIG_TXT.OFTP.Maxbufsize;
            self.data.CONFIG_TXT.Net1.TCPMaxSendBuf = self.data.CONFIG_TXT.OFTP.Maxbufsize;

            self.data.CONFIG_TXT.Net1.TCPMaxRecvTO = self.data.CONFIG_TXT.OFTP.Timeout;
            self.data.CONFIG_TXT.Net1.TCPMaxSendTO = self.data.CONFIG_TXT.OFTP.Timeout;
        }

        if (self.data.CONFIG_TXT.Service.ServiceType === 4) {
            self.data.CONFIG_TXT.Net1.TCPMaxRecvBuf = self.data.CONFIG_TXT.Monitor.MaxRecvBuf;
            self.data.CONFIG_TXT.Net1.TCPMaxSendBuf = self.data.CONFIG_TXT.Monitor.MaxSendBuf;

            self.data.CONFIG_TXT.Net1.TCPMaxRecvTO = self.data.CONFIG_TXT.Monitor.Timeout;
            self.data.CONFIG_TXT.Net1.TCPMaxSendTO = self.data.CONFIG_TXT.Monitor.Timeout;
        }

        return self.data;
    }

    function ruleSchedules() {// Schedules

        return self.data;
    }

    function ruleFileType() {// File Type

        return self.data;
    }

    function ruleFileTypeGlobal() {// File Type Global

        return self.data;
    }

    function ruleOperator() {// Operator
        try {
            // Se não houve mudança na senha, retirar o campo para não corromper a senha previamente cadastrada.
            if (self.form.opSenha.$pristine) {
                delete self.data.CONFIG_TXT.Operator.Senha;
            }
        } catch (eX) {
            console.log(eX.message);
        }

        return self.data;
    }

    function ruleGroup() {// Group

        return self.data;
    }

    function ruleErrorEvents() {// Code Error and Code Event

        return self.data;
    }

    function onPersistSuccess() {
        var msg = t('Registro') + " " + (self.data.ID === 0 ? t('adicionado') : t('atualizado')) + " " +
            t('com sucesso') + "!";

        if (self.redirect) {
            StcpUtilsService.showToast("info", "Info.", msg,
                StcpUtilsService.getStateRedirectByJson(self.data), self.paramsRedirect);
        } else {
            // Mostra o toastr de sucesso.
            StcpUtilsService.showToast("info", "Info.", msg);

            if (self.refresh) {
                // Resolve novamente o objeto.
                $state.transitionTo($state.current, $state.$current.params, {
                    reload: self.refresh,
                    inherit: false,
                    notify: true
                });
            }

            // Atualiza cookie de Operator.
            if (self.data.Entity.Name == "operator")
                _storage.set('Operator', self.data);

            // Limpando dados do scope.
            if ($rootScope.data !== null && $rootScope.data !== undefined)
                delete $rootScope.data;

            if ($rootScope.form !== null && $rootScope.form !== undefined)
                delete $rootScope.form;

            if ($rootScope.$scope !== null && $rootScope.$scope !== undefined)
                delete $rootScope.$scope;

            if (self.data)
                delete self.data;
        }
    }

    function onPersistError(response) {
        if (response && response.status && response.statusText) {
            var err = response.statusText && response.data ? response.statusText + ': ' + response.data :
                t("Nenhum dado retornado, verifique arquivo de log e se o serviço REST está sendo executado!");

            if (self.redirect) {
                StcpUtilsService.showToastError(t("Erro"), err,
                    StcpUtilsService.getStateRedirectByJson(self.data), self.paramsRedirect);
            } else {
                StcpUtilsService.showToastError(t("Erro"), err);
            }
        }
    }

    self = {
        setData: function (args) {// Set Entity to rule.
            // Limpar buffers.
            self.data = null;
            self.form = null;
            self.redirect = null;
            self.refresh = null;

            // Remove do objeto principal.
            delete self.data;
            delete self.form;
            delete self.redirect;
            delete self.refresh;

            if (self.paramsRedirect) {
                if (self.paramsRedirect.user_id)
                    delete self.paramsRedirect.user_id;
                if (self.paramsRedirect.instance_id)
                    delete self.paramsRedirect.instance_id;

                delete self.paramsRedirect;
            }

            // Copia os novos valores para manipulação.
            self.data = angular.copy(args.data);
            self.form = angular.copy(args.form);
            self.paramsRedirect = {};
            self.redirect = args.redirect !== undefined ? angular.copy(args.redirect) : true;
            self.refresh = args.refresh !== undefined ? angular.copy(args.refresh) : true;

            if (self.data.INSTANCE_ID) {
                self.paramsRedirect = self.paramsRedirect === undefined ? {} : self.paramsRedirect;
                self.paramsRedirect.instance_id = self.data.INSTANCE_ID;
            }

            if (self.data.USER_ID) { // User File Type
                self.paramsRedirect = self.paramsRedirect === undefined ? {} : self.paramsRedirect;
                self.paramsRedirect.user_id = self.data.USER_ID;
                self.paramsRedirect.instance_id = $stateParams.instance_id;
            }

            if (args.user_id && args.instance_id) {
                self.paramsRedirect = self.paramsRedirect === undefined ? {} : self.paramsRedirect;
                self.paramsRedirect.instance_id = args.instance_id;
                self.paramsRedirect.user_id = args.user_id;
            }

            // Retorna o novo objeto.
            return self;
        },
        applyRules: function () {
            switch (self.data.Entity.Name) {
                case 'instance':
                    return ruleInstances();
                case 'user':
                    return ruleUsers();
                case 'service':
                    return ruleServices();
                case 'schedule':
                    return ruleSchedules();
                case 'filetype':
                    return ruleFileType();
                case 'filetypeglobal':
                    return ruleFileTypeGlobal();
                case 'operator':
                    return ruleOperator();
                case 'group':
                    return ruleGroup();
                case 'errors_event':
                    return ruleErrorEvents();
            }
        },
        onPersistSuccess: onPersistSuccess,
        onPersistError: onPersistError
    };

    return self;
}

})();

I’m applying the test as follows:

describe('Testing BusinessLogicService', function () {
beforeEach(module('app'));

var rootScope, state, stateParams, StcpUtilsService, StorageService, storage, language, httpBackend; 
var srv; 

describe('Testing BusinessLogicService', function () {
beforeEach(module('app'));

var rootScope, state, stateParams, StcpUtilsService, StorageService, storage, language, httpBackend; 
var srv; 

beforeEach(inject(function (BusinessLogicService, $rootScope, $state, $stateParams, StcpUtilsService, StorageService, storage, LanguageResource, $httpBackend) {        
    rootScope = $rootScope;
    srv = BusinessLogicService;
    state = $state;
    stateParams = $stateParams;
    StcpUtilsService = StcpUtilsService; 
    StorageService =StorageService; 
    storage = storage;
    language = LanguageResource; 
    httpBackend = $httpBackend;  

    var fakeRequest = function(){
        return;
    }; 

    httpBackend = $httpBackend;
    httpBackend.when('GET', './configs/config.json').respond(fakeRequest);
    httpBackend.when('GET', './configs/modules.json').respond(fakeRequest);
    httpBackend.when('GET', './configs/app_ver').respond(fakeRequest);
    httpBackend.when('GET', './configs/trans_tab.json').respond(fakeRequest);
    httpBackend.when('GET', './json/pt-br.json').respond(fakeRequest);
    httpBackend.when('GET', './json/es.json').respond(fakeRequest);
    httpBackend.when('GET', './json/en-gb.json').respond(fakeRequest);

    // var self = this;          


})); 

it('testing function onPersistSuccess', function(){
    self = {
        data:{
            ID: 0
        }
    }
    srv.onPersistSuccess();
});


})
  • In your code you have $emit(), however none $on() is set -where, I imagine, the payload containing the property ID:'' would be applied to the scope. As it stands, your Undefined occurs because self.data is not populated.

  • @Onosendai self = this, how this interferes with my test. How this is influencing this function?

  • this, in the context mentioned, is the internal scope of the function BusinessLogicService() - something completely other than $scope and $rootScope. self.data, its return, does not receive at any time the payload used in $emit().

  • @Onosendai I took the rootScope. $Mit and keeps giving the same error.

No answers

Browser other questions tagged

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