angularjs - 如何使用已编译元素在单元测试中访问 c​​ontrollerAs 命名空间?

标签 angularjs unit-testing controller directive

在这个 fiddle http://jsfiddle.net/FlavorScape/fp1kktt9/我尝试在 Controller 上设置属性,而不是直接在 $scope 上。在模板(生产中)中,我们只做 myAliasCtrl.somePropertyList 并且 ng-repeat 工作。

但是,这在测试中不起作用。我不知道如何获取/分配 Controller 上的属性。

更新:
我的测试环境中一定有一些奇怪的本地化问题,因为我确实让 ng-repeat 工作。请注意如何有两个子元素,即使该属性位于别名 Controller 上。 http://jsfiddle.net/FlavorScape/2adn983y/2/

但是,我的问题仍然是,我将如何获得对该已编译 Controller 的引用来创建 spy ? (或者只是获取对别名 Controller 的引用)?

这是来源:

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');

    });
});

最佳答案

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

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

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

这里是 updated fiddle .

更新:

您正在使用 controllerAs ,基本上你得到 Controller 的this绑定(bind)到范围属性。例如。 controllerAs: 'myTestCtrl'隐含结果为 $scope.myTestCtrl = this; (其中 this 是 Controller 实例。

但是你又在哪里试图访问错误的元素。您需要包装的第一个子元素 <div>然后你需要它的隔离范围(不是正常范围):
var ctrl = el.children().first().isolateScope().myTestCtrl;

Another updated fiddle

关于angularjs - 如何使用已编译元素在单元测试中访问 c​​ontrollerAs 命名空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25189304/

相关文章:

javascript - 将 HTML/CSS 元素转换为可重用的 AngularJS 指令?

javascript - 我可以在编写 TypeScript 单元测试时对依赖项进行猴子补丁吗

java - Maven:在不同的源级别上编译和测试

java - EasyMock 不区分子类

c# - 我可以接受 HttpPostedFileBase 作为 ViewModel 的一部分吗

javascript - 如何在单独的文件中定义 Controller

controller - AngularJS:在不完全重新加载 Controller 的情况下更改哈希和路由

php - Laravel 5.1 - 表格的拆分内容

java - Spring:使模型可供 Controller 使用的正确方法?

javascript - 在新选项卡中打开 Blob Url (IE)