Html in AngulaJS does not change when I test with an alias controller

38 Views Asked by At

I have a problem in AngularJS, to test a html div with a dynamic value when I use controller's alias

Here my code

<div id="title_contract" class="caption">{{ ctrl.detail_title }}</div>

where crtl is the ContractController's alias.

My test is

    describe('Testing create new or open detail contract', function() {
        var template, ctrl, scope;
        beforeEach(inject(function ($controller, $compile) {
            scope = $rootScope.$new();
            ctrl = $controller('ContractController', {$scope: scope});
            var element = angular.element('<div id="title_contract" class="caption">{{ ctrl.detail_title }}</div>');
            template = $compile(element)(scope);
        }));

        it('should prepare variable to create new contract', function () {
            ctrl.create_clicked();

            scope.$digest();
            var templateAsHtml = template.html();

            expect(templateAsHtml).toContain('New Contract');
        });
    }

MyController is

PageApp.controller('ContractController', function($rootScope, $scope ) {

  var vm = this;
  vm.create_clicked       = doCreate;
  vm.title_detail         = '';

  function doCreate() {
     vm.detail_title = 'New Contract';
  }});

When I call create_clicked the title in vm change its value but test fails 'cos the div value is empty.

I try to use $scope (so without alias) and it works. But I'd like to use alias approach.

Did somebody encounter this problem? Thanks' in advance

1

There are 1 best solutions below

1
On BEST ANSWER

Try:

ctrl = $controller('ContractController as ctrl', {$scope: scope});

See $controller documentation:

The string can use the controller as property syntax