Mocking Controller Instantiation In Angular Directive Unit Test

前端 未结 1 1012
清歌不尽
清歌不尽 2021-01-31 09:30

I am unit testing an Angular directive and would like to mock or stub in some way the instantiation of the named controller in the unit test.

So first I suppose on to s

1条回答
  •  既然无缘
    2021-01-31 09:59

    You can create mocks in module configuration block by using $controllerProvider.register() for controllers, $provide.provider(), $provide.factory(), $provide.service() and $provide.value() for providers, factories and services:

    JavaScript

    beforeEach(function () {
        module('App.Directives.BreadCrumbs', function($provide, $controllerProvider) {
            $controllerProvider.register('BreadCrumbsController', function($scope) {
                // Controller Mock
            });
            $provide.factory('someService', function() {
                // Service/Factory Mock
                return {
                    doSomething: function() {}
                }
            });
        });
    });
    

    Once you do so, Angular will inject your mock BreadCrumbsController controller into kxBreadcrumbs directive. This way you don't need to include real controller and it's dependencies into unit test.

    For more information see Angular's official documentation on:

    • $provide
    • $controllerProvider

    0 讨论(0)
提交回复
热议问题