如何使用编译元素在单元测试中访问controllerAs命名空间?

2023-12-14

在这个小提琴里http://jsfiddle.net/FlavorScape/fp1kktt9/我尝试在控制器上设置属性,而不是直接在 $scope 上设置属性。在模板(在生产中)中,我们只执行 myAliasCtrl.somePropertyList ,并且 ng-repeat 起作用。

然而,这在测试中不起作用。我不知道如何获取/分配控制器上的属性。

UPDATE:我的测试环境中一定遇到了一些奇怪的局部问题,因为我确实让 ng-repeat 正常工作。请注意如何有两个子元素,即使该属性位于别名控制器上。http://jsfiddle.net/FlavorScape/2adn983y/2/

然而,我的问题仍然是,我如何获得对已编译控制器的引用来创建间谍?(或者只是获取对别名控制器的引用)?

这是来源:

angular.module('myApp', [])
.directive('myTestDirective', function () {
    return {
        restrict: 'E',
        scope: {
            myBinding: '='
        },
        replace: true,
        template: '<div ng-if="isRendered">TEST<div ng-repeat="foo in myCtrl.fooList">{{foo}}</div></div>',
        controller: 'myTestController',
        controllerAs: 'myCtrl'
    };
})
.controller('myTestController', function($scope) {
    $scope.isRendered = true;
     // if i reference this, ng-repeat works
    $scope.fooList = ["boob","cat", "Tesla"];
});

describe('myTest directive:', function () {
    var scope, compile, validHTML;

    validHTML = '<div><my-test-directive my-binding="isRendered"></my-test-directive></div>'; //i

    beforeEach(module('myApp'));

    beforeEach(inject(function($compile, $rootScope){
        scope = $rootScope.$new();        
        scope.isRendered = true;

        compile = $compile;
    }));

    function create() {
        var elem, compiledElem;
        elem = angular.element(validHTML);
        compiledElem = compile(elem)(scope);
        scope.$digest();
        return compiledElem;    
    }

    it('should have a scope on root element', function () {  
        var el = create();

        // how to get the controller???
        el.scope().myCtrl.fooList =  ["monkey","apple","Dishwasher"];

        // notice it just has <!-- ng-repeat
        console.log( el );


        expect(el.text()).toContain('TEST');

    });
});

一切都按预期进行:)您只是试图访问错误的范围。

Because ngIf创建一个新范围,您应该访问该范围(因为isRendered是在该子作用域上创建的:

expect(el.children().first().scope().isRendered).toBeTruthy();

这里是更新了小提琴.


UPDATE:

您正在使用controllerAs,基本上你得到了控制器的this绑定到范围属性。例如。controllerAs: 'myTestCtrl'隐含地导致$scope.myTestCtrl = this; (where this是控制器实例。

但你又试图访问错误的元素。您需要包装的第一个子元素<div>然后你需要它的隔离范围(不是正常范围):

var ctrl = el.children().first().isolateScope().myTestCtrl;

另一个更新的小提琴

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用编译元素在单元测试中访问controllerAs命名空间? 的相关文章

随机推荐