首页 > 解决方案 > 如何从控制器监视服务方法?

问题描述

我正在为控制器编写 UT,在尝试实现 commandRouter.execute 方法(请参阅第二规范)时,我收到错误消息:无法读取未定义的属性“执行”。

有人可以让我知道我在这里做错了什么以及从控制器监视方法的正确方法是什么。?

module.controller('DcsPlus.AP.OmsControl.omsMasterRecipeDialogPopUpController', omsMasterRecipeDialogPopUpController);
    
    omsMasterRecipeDialogPopUpController.$inject = [
        'DcsPlus.Frame.Logic.commandRouter'
    ];

    function omsMasterRecipeDialogPopUpController(commandRouter) {
        var vm = this;

    vm.execute = function(command) {
        commandRouter.execute(command);
    };
} 

控制器.spec.js

    describe('omsMasterRecipeDialogPopUpController', function () {

    var omsMasterRecipeDialogPopUpControllerTest;
    var commandRouterMock;
    var $scope;

    beforeEach(function () {
        registerMockServices();
        prepareCommandRouterMock();
    });


    describe('execute', function () {
        it('1. Should check if execute method is defined', function() {
            expect(omsMasterRecipeDialogPopUpControllerTest.execute).toBeDefined();
        });

        it('2. Should check if execute method of commandRouter is called', function() {
            omsMasterRecipeDialogPopUpControllerTest.execute();
            expect(commandRouterMock.execute).toHaveBeenCalled();
        });

    });

    function prepareCommandRouterMock() {
        commandRouterMock = {
            execute: function() {
            }
        };
    }

     /*beforeEach(function () {
         commandRouterMock = jasmine.createSpyObj('DcsPlus.Frame.Logic.commandRouter', ['execute']);
     });*/

    function registerMockServices() {
        angular.mock.module('DcsPlus.AP.OmsControl', function ($provide) {
            $provide.value('DcsPlus.Frame.Logic.commandRouter', commandRouterMock);
        });


        angular.mock.inject(['$controller', '$rootScope', 'dialogService',
            function ($controller, $rootScope, dialogService) {
            $scope = $rootScope.$new();
            spyOn(commandRouterMock, 'execute').and.callThrough();

            // Init the controller, passing our spy service instance
            omsMasterRecipeDialogPopUpControllerTest = $controller('DcsPlus.AP.OmsControl.omsMasterRecipeDialogPopUpController', {
                $scope: $scope
            });
        }]);
    }
});

标签: angularjsunit-testingjasmine

解决方案


一开始您创建commandRouterMock但从不将其分配给任何东西。

尝试这个:

beforeEach(function () {
    registerMockServices();
    commandRouterMock = prepareCommandRouterMock();
});

function prepareCommandRouterMock() {
    return {
         execute: function() {
        }
    };
}

推荐阅读