mercredi 6 juillet 2016

How to mock/stub activate() method in AngularJS application

I'm currently working on a large AngularJS application, very much based on the excellent AngularJS Styleguide by John Papa.

One of his recommendations is the use of an activate() method as a sort of bootstrapper for every controller. This makes your code structure clear and you immediately know where bootstrapping begins. Often times, I use it to load data (I prefer this over route-resolves).

The problem I'm facing is how should I unit-test the methodUnderTest()-method in the below code example without running the activate()-method.

(function() {
    'use strict';

    angular
        .module('myApp', [])
        .controller('ControllerUnderTest', ControllerUnderTest);

    ControllerUnderTest.$inject = [];

    /* @ngInject */
    function ControllerUnderTest() {
        var vm = this;

        // attach functions to vm
        vm.activate = activate;
        vm.methodUnderTest = methodUnderTest;

        // activate
        activate();

        function activate() {
            // controller start-up logic
        }

        function methodUnderTest() {
            // how to test this method, without running the activate() method
        }
})();

Below is the test-code I currently have, but as you would expect it will always run the activate() method (which is not what I want).

(function() {

    var scope, createController;

    beforeEach(module('myApp'));

    describe('ControllerUnderTest', function(){
        beforeEach(inject(function($rootScope, $controller) {
            scope = $rootScope.$new();

            createController = function() {
                return $controller('ControllerUnderTest', { 'scope': scope });
            };
        }));

        it('should be defined', function() {
            var controller = createController();
            expect(controller).toBeDefined();
        });

        it('should have a methodUnderTest', function() {
            var controller = createController();
            expect(controller.methodUnderTest).toBeDefined();
        });

    });
})();

How do I test ControllerUnderTest.methodUnderTest() without running the activate() method?

Aucun commentaire:

Enregistrer un commentaire