mercredi 6 mai 2015

AngularJS - Correct way to mock controller dependencies

I'm confused about which is the correct way to mock controller dependencies in angular tests: Let's say I have a controller with one dependency (MyFactory):

angular.module('app').controller('AppCtrl', function($scope, MyFactory) { 
    $scope.test = function() {
        MyFactory.print();
    };
});

1)

'use strict';

describe('Controller: AppCtrl', function() {
    beforeEach(module('app'));

    var scope, controller;

    it('scope.test() - should call function MyFactory.print', inject(function(MyFactory) {
        spyOn(MyFactory, 'print');

        createController();

        scope.test();

        expect(MyFactory.print).toHaveBeenCalled();   
    }));

    /////////////////////////////////////////

    function createController(locals) {
        locals = locals || {};

        inject(function($controller, $rootScope) {
            scope  = $rootScope.$new();
            locals = angular.extend({$scope: scope}, locals);

            controller = $controller('AppCtrl', locals);
        });
    }

});

2)

'use strict';

describe('Controller: AppCtrl', function() {
    beforeEach(module('app'));

    var scope, controller;

    it('scope.test() - should call function MyFactory.print', function(MyFactory) {
        var locals = {
            MyFactory: jasmine.createSpyObj('MyFactory', ['print'])
        };

        createController(locals);

        scope.test();

        expect(locals.MyFactory.print).toHaveBeenCalled();   
    });

    /////////////////////////////////////////

    function createController(locals) {
        locals = locals || {};

        inject(function($controller, $rootScope) {
            scope  = $rootScope.$new();
            locals = angular.extend({$scope: scope}, locals);

            controller = $controller('AppCtrl', locals);
        });
    }

});

Whats the correct way? using jasmine.createSpyObj and inject the mocked dependencies when create the controller or create a spy using spyOn and then create the controller?

Aucun commentaire:

Enregistrer un commentaire