vendredi 25 mars 2016

How do I unit test further .then and .catch branching in an Angular controller?

(function() {
    'use strict';

    angular
        .module('walletInformation')
        .controller('WalletInformationController', WalletInformationController);

    /* @ngInject */
    function WalletInformationController(
        $q,
        $scope,
        config,
        logger,
        session,
        $interpolate,
        flowstack,
        profileService,
        walletInformationFormlyService,
        postMsg
    ) {
        // jshint validthis: true
        var vm = this;
        var app = $scope.app;
        var user = session.get('profile').profile || {};

        vm.saveWalletInformation = saveWalletInformation;
        vm.onClickCancel = onClickCancel;
        vm.deleteWallet = deleteWallet;
        vm.model = {
            walletInformation : {
                firstName: user.name.first,
                lastName: user.name.last,
                emailAddress: user.emailAddress,
                phoneNumber: user.mobilePhone.phoneNumber,
                keepMeUpdated: user.preferences.receiveEmailNotification
            }
        };

        activate();

        ////////////////

        /**
         * @function activate
         * @description init function for the controller
         * Calls paymentCard to get the
         * */
        function activate() {
            createFormFields();
            logger.info('Activated the Wallet Information View.');
        }

        function createFormFields() {
            vm.fields = walletInformationFormlyService.getFormlyFields($scope.app.text);
        }

        function saveWalletInformation() {
            var updatedProfile = createLegacyProfileInformation();

            profileService.updateProfileInformation(updatedProfile).then(onSuccess).catch(onError);

            function onSuccess(response) {
                session.set('profile', {
                    profile: response.profile
                });

                if (vm.model.walletInformation.currentPassword && vm.model.walletInformation.newPassword) {
                    changePasswordRequest();
                } else {
                    flowstack.add('accountManagement');
                    flowstack.next();
                }

            }

            function onError(error) {
                logger.error('Verify save Wallet Information Error: ', error);
            }

            //changePassword
            function changePasswordRequest() {
                var updatedPassword = {
                    data: {
                        currentPassword: vm.model.walletInformation.currentPassword,
                        newPassword: vm.model.walletInformation.newPassword
                    }
                };

                profileService
                    .changePassword(updatedPassword)
                        .then(onChangePasswordSuccess, onChangePasswordError);

                function onChangePasswordSuccess(response) {
                    flowstack.add('accountManagement');
                    flowstack.next();
                    logger.info('Change password request: ', response);
                }

                function onChangePasswordError(response) {
                    logger.error('Change Password Error: ', response);
                }
            }

        }

        function deleteWallet() {
            var appText = app.text.walletInformation;
            console.log(appText);
            flowstack.add('confirmation');
            flowstack.next({
                data: {
                    title: appText.deleteWalletConfirmationTitle,
                    body: appText.deleteWalletConfirmationBody,
                    cancelButton: appText.deleteWalletConfirmationCancelButton,
                    confirmButton: appText.deleteWalletConfirmationConfirmButton,
                    onConfirm: function() {
                        profileService.deleteWallet().then(deleteProfileSuccess, deleteProfileFailure);

                        function deleteProfileSuccess(response) {
                            if (response.profile) {
                                logger.info('profile is successfully deleted.', response);
                                postMsg.send('closeSwitch');
                            }
                        }

                        function deleteProfileFailure(error) {
                            logger.error('something went wrong while deleting profile.', error);
                        }
                    },
                    onCancel: function() {
                        flowstack.add('walletInformation');
                        flowstack.next();
                    }
                }
            });
        }

        function createLegacyProfileInformation() {
            var updatedProfile = user;
            var formlyField = vm.model.walletInformation;

            //Update the profile
            updatedProfile.name = {
                first: formlyField.firstName,
                last: formlyField.lastName
            };
            updatedProfile.mobilePhone.phoneNumber = formlyField.phoneNumber;
            updatedProfile.preferences.receiveEmailNotification = formlyField.keepMeUpdated;

            return {
                data: updatedProfile
            };
        }
        function onClickCancel() {
            flowstack.back();
        }
    }
})();

Coverage is saying that onSuccess of saveWalletInformation and changePasswordRequest isnt't covered but I'm not sure exactly how to test it, the only thing I've tested now is that the saveWalletInformation function is calling the profile service:

describe.only('WalletInformationController ---', function() {
    var controller, scope;
    var userProfile = {
        profile: {
            name: {
                first: 'someonefirstname',
                last: 'someoneslastname'
            },
            emailAddress: 'someone@something.com',
            mobilePhone: {
                countryCode: 'US+1',
                phoneNumber: '123 212 2342'
            },
            preferences: {
                receiveEmailNotification: true
            }
        }
    };

    beforeEach(function() {
        bard.appModule('walletInformation');
        bard.inject(
            '$q',
            '$controller',
            '$rootScope',
            'api',
            'flowstack',
            'logger',
            'session',
            'profileService'
        );

        session.set('profile', userProfile);
    });

    beforeEach(function() {
        sandbox = sinon.sandbox.create();
        scope = $rootScope.$new();
        scope.app = {
            text: {
                global: {},
                walletInformation: {
                    deleteWalletConfirmationTitle: 'Confirm Wallet Deletion?'
                },
                userInformation: {
                    emailValidation: 'Please enter valid email'
                },
                signin: {
                    rememberMeLabel: 'remember me'
                }
            }
        };

        controller = $controller('WalletInformationController', {
            $scope: scope
        });

        loggerErrorStub = sandbox.stub(logger, 'error');

        sandbox.stub(logger, 'info');

        controller = $controller('WalletInformationController', {
            $scope: scope
        });
    });

describe('saveWalletInformation method', function() {
    beforeEach(function() {
        // apiStub.restore();
        sandbox.stub(profileService, 'updateProfileInformation', function() {
            return $q.when(userProfile);
        });
    });

    it('should saveWalletInformation successfully', function() {

        controller.saveWalletInformation();
        expect(profileService.updateProfileInformation).to.have.been.called;
    });

    it('should log error msg when saveWalletInformation call fails', function() {

        profileService.updateProfileInformation.restore();

        sandbox.stub(profileService, 'updateProfileInformation', function() {
            return $q.reject();
        });

        controller.saveWalletInformation();
        scope.$apply();

        expect(loggerErrorStub).to.have.been.calledOnce;
    });

    it('should call changePasswordRequest when currentPassword and newPassword are set', function() {
        sandbox.stub(profileService, 'changePassword', function() {
            return $q.when({
                success: true,
                extensionPoint: null
            });
        });

        sandbox.stub(flowstack, 'add');
        sandbox.stub(flowstack, 'next');

        controller.saveWalletInformation();

        // scope.$apply();
        // expect(flowstack.next).to.have.been.calledOnce;
        // expect(flowstack.add).to.have.been.calledOnce;
        expect(profileService.updateProfileInformation).to.have.been.called;
        // expect(profileService.changePassword).to.have.been.called;
    });
});

Aucun commentaire:

Enregistrer un commentaire