How to inject a controller into a directive when unit-testing

南楼画角 提交于 2019-12-03 03:57:08

I think there is a simpler way than the accepted answer, which doesn't require creating a new module.

You were close when trying $provide, but for mocking controllers, you use something different: $controllerProvider. Use the register() method in your spec to mock out your controller.

beforeEach(module('myApp', function($controllerProvider) {
    $controllerProvider.register('customerContoller', function($scope) {
        // Controller Mock
    });
});

One way is to define a new module (e.g. 'specApp') that declares your app (e.g. 'myApp') as a dependency. Then register a 'customerController' controller with the 'specApp' module. This will effectively "hide" the customerController of 'myApp' and supply this mock-controller to the directive when compiled.
E.g.:

Your app:

var app = angular.module('myApp', []);
...
app.controller('customerController', function ($scope,...) {
    $scope = {...};
    ...
});
app.directive('myCustomer', function () {
    return {
        template: 'cust.html',
        controller: 'customerController'
    };
});

Your spec:

describe('"myCustomer" directive', function () {
    $compile;
    $newScope;

    angular.module('specApp', ['myApp'])
    /* Register a "new" customerController, which will "hide" that of 'myApp' */
    .controller('customerController', function ($scope,...) {
        $scope = {...};
        ...
    });

    beforeEach(module('specApp'));

    it('should do cool stuff', function () {
        var elem = angular.element('<div my-customer></div>');
        $compile(elem)($newScope);
        $newScope.$digest();
        expect(...
    });
});

See, also, this working demo.

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