加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

单元测试 – 嵌套控制器的单元测试

发布时间:2020-12-17 09:03:15 所属栏目:安全 来源:网络整理
导读:我正在为一个嵌套的控制器编写单元测试,但是无法弄清我在测试中如何模拟同样的行为. 我有2个控制器 function FirstController ($scope) { $scope.childs = [{ title : 'Hello,earth!' }];};function SecondController ($scope) { $scope.child.title = $scop
我正在为一个嵌套的控制器编写单元测试,但是无法弄清我在测试中如何模拟同样的行为.

我有2个控制器

function FirstController ($scope) {
    $scope.childs = [{
         title : 'Hello,earth!'
    }];
};

function SecondController ($scope) {
    $scope.child.title = $scope.child.title + $scope.$index;
};

在我的HTML中:

<div data-ng-controller="FirstController">
    <div data-ng-repeat="child in childs" data-ng-controller="SecondController">
        {{ child.title }}
    </div>
</div>

这样可以预期(http://jsfiddle.net/tcayp/1/)

单位测试:

// FirstController
it('Should have childs',function () {
    scope = {};
    ctrl = new FirstController(scope);
    expect(scope.childs.length).toBeGreaterThan(0);
});
// SecondController
it('Should have inherited a child',function () {
    scope = {};
    ctrl = new SecondController(scope);
    expect(scope.child.title).toEqual('Hello,earth!0');
});

在第二次控制器测试中,我无法弄清楚如何从ng-repeat模拟继承链.

理想情况下,使用单元测试,我们将单独测试类(单位).在一个测试中测试2控制器可能太多:测试将变得更加复杂和更脆弱.

仔细观察所提供的示例,可能会注意到,实际上并不是测试2个控制器,而是确保数据在父范围内可用.所以,只关注一个控制器(SecondController)和继承的数据,可以这样写一个测试:

describe('Testing the SecondController controller',function() {

    var $parentScope,$scope,ctrl;
    it('should prepare title',inject(function($rootScope,$controller) {

        //setup hierarchy of scopes with data             
        $rootScope.childs = [{
            title : 'Hello,earth!'
        }];
        $scope = $rootScope.$new();
        $scope.$index = 1;

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

        expect($scope.childs[0].title).toEqual('Hello,earth!1');        
    }));
});

这是完整的jsFiddle:http://jsfiddle.net/pkozlowski_opensource/h8xry/13/

我真的建议不要一起测试两个控制器,只是为了回答这个问题,这也是可能的:

describe('Testing the SecondController controller',function() {

    it('should prepare title',$controller) {

        $controller('FirstController',{
            $scope: $rootScope
        });

        var $scope = $rootScope.$new();
        $scope.$index = 1;

        ctrl = $controller('SecondController',earth!1');        
    }));
});

和jsFiddle:http://jsfiddle.net/pkozlowski_opensource/4Qy6b/1/

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读