Mocking Controller Instantiation In Angular Directive Unit Test

橙三吉。 提交于 2019-12-02 17:09:20
Vadim

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:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!