如何通过父元素测试Component Bindings的更改?

时间:2018-01-04 18:56:54

标签: angularjs unit-testing jasmine components angularjs-components

我有一个类似于下面的组件,并希望测试mgo.Index方法在绑定type Index struct { Key []string // Index key fields; prefix name with dash (-) for descending order Unique bool // Prevent two documents from having the same index key DropDups bool // Drop documents with the same index key as a previously indexed one Background bool // Build index in background and return immediately Sparse bool // Only index documents containing the Key fields // If ExpireAfter is defined the server will periodically delete // documents with indexed time.Time older than the provided delta. ExpireAfter time.Duration // Name holds the stored index name. On creation if this field is unset it is // computed by EnsureIndex based on the index key. Name string // Properties for spatial indexes. // // Min and Max were improperly typed as int when they should have been // floats. To preserve backwards compatibility they are still typed as // int and the following two fields enable reading and writing the same // fields as float numbers. In mgo.v3, these fields will be dropped and // Min/Max will become floats. Min, Max int Minf, Maxf float64 BucketSize float64 Bits int // Properties for text indexes. DefaultLanguage string LanguageOverride string // Weights defines the significance of provided fields relative to other // fields in a text index. The score for a given word in a document is derived // from the weighted sum of the frequency for each of the indexed fields in // that document. The default field weight is 1. Weights map[string]int // Collation defines the collation to use for the index. Collation *Collation } 更改时的作用。

我整个上午都试过,但找不到办法解决这个问题。

$onChange

我希望我的测试表现得像是更改绑定值的组件父级。

myBinding

这可能吗?怎么样? 任何提示? Plunker,CodePen或其他示例?

1 个答案:

答案 0 :(得分:3)

测试AngularJS组件与测试指令没有多大区别。

要测试控制器的方法/属性,可以使用element.controller("componentName") method访问组件控制器的实例(componentName - 是camelCase指令/组件名称)。

以下是使用$compile service测试组件和$onChanges挂钩的示例:

angular.module('myApp', [])
.component('myComponent', {
    bindings: {
        myBinding: '<'
    },
    template: '<div>{{$ctrl.result}}</div>',
    controller: 'myComponentController'
})
.controller('myComponentController', ['$filter', 'myService', function myComponentController($filter, myService) {
    var ctrl = this;

    ctrl.$onInit = onInit;
    ctrl.$onChanges = onChanges;

    function onInit() {
        ctrl.result = ctrl.myBinding;
    }

    function onChanges(changes) {
        if (angular.isDefined(changes.myBinding)) {
            if (angular.isDefined(changes.myBinding.currentValue)) {
                if (!angular.equals(changes.myBinding.currentValue, changes.myBinding.previousValue)) {
                    myService.doSomething(changes.myBinding.currentValue).then(
                        function (data) {
                            ctrl.result = data; 
                        }
                    );
                }
            }
        }
    }
}])
.service('myService', ['$timeout', function ($timeout) {
    return {
        doSomething: function (x) {
            return $timeout(function () {
                return x * 3;
            }, 500);
        }
    };
}]);


/*
TEST GO HERE 
*/

describe('Testing a component controller', function() {
  var $scope, ctrl, $timeout, myService;
  
    beforeEach(module('myApp', function ($provide) {

    }));
  
    beforeEach(inject(function ($injector) {
        myService = $injector.get('myService');
        $timeout = $injector.get('$timeout');
    }));
  
    describe('with $compile', function () { 
        var element;
        var scope;
        var controller;
        
        beforeEach(inject(function ($rootScope, $compile) {
            scope = $rootScope.$new();
            scope.myBinding = 10;
            element = angular.element('<my-component my-binding="myBinding"></my-component>');
            element = $compile(element)(scope);
            controller = element.controller('myComponent');
            scope.$apply();
        }));
      
        
         it('should render template', function () {
           expect(element[0].innerText).toBe('10'); //initial
           $timeout.flush(); //onchanges happened and promise resolved from the service
           //undefined -> 10
           expect(element[0].innerText).toBe('30'); 
         });
         
         
         it('should reflect to changes', function () {
           spyOn(myService, "doSomething").and.callThrough();
           scope.myBinding = 15; //change the binding
           scope.$apply(); //we need to call $apply to pass the changes down to the component
           $timeout.flush();
           expect(myService.doSomething).toHaveBeenCalled(); // check if service method was called 
           expect(controller.result).toBe(45); // check controller's result value 
         });
         
    })

});
.as-console-wrapper {
  height:0;
}
<!DOCTYPE html>
<html>

  <head>
    <!-- jasmine -->
    <script src="//cdnjs.cloudflare.com/ajax/libs/jasmine/2.8.0/jasmine.js"></script>
    <!-- jasmine's html reporting code and css -->
    <script src="//cdnjs.cloudflare.com/ajax/libs/jasmine/2.8.0/jasmine-html.js"></script>
    <link href="//cdnjs.cloudflare.com/ajax/libs/jasmine/2.8.0/jasmine.css" rel="stylesheet" />
    
    <script src="//cdnjs.cloudflare.com/ajax/libs/jasmine/2.8.0/boot.js"></script>
    <!-- angular itself -->
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.js"></script>
    <!-- angular's testing helpers -->
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-mocks.js"></script>
  </head>

  <body>
    <!-- bootstrap jasmine! -->
  <script>
    var jasmineEnv = jasmine.getEnv();
    
    // Tell it to add an Html Reporter
    // this will add detailed HTML-formatted results
    // for each spec ran.
    jasmineEnv.addReporter(new jasmine.HtmlReporter());
    
    // Execute the tests!
    jasmineEnv.execute();
  </script>
  </body>

</html>

您还可以使用$componentController service测试您的组件。但在这种情况下,您需要在测试中显式调用生命周期钩子,例如:

ctrl = $componentController('myComponent', {$scope: scope}, { myBinding: 10 });
ctrl.$onInit();

要测试$onChanges挂钩,您需要传递一个“正确”构造的更改对象作为参数:

angular.module('myApp', [])
    .component('myComponent', {
        bindings: {
            myBinding: '<'
        },
        template: '<div>{{$ctrl.result}}</div>',
        controller: 'myComponentController'
    })
    .controller('myComponentController', ['$filter', 'myService', function myComponentController($filter, myService) {
        var ctrl = this;

        ctrl.$onInit = onInit;
        ctrl.$onChanges = onChanges;

        function onInit() {
            ctrl.result = ctrl.myBinding;
        }

        function onChanges(changes) {
            if (angular.isDefined(changes.myBinding)) {
                if (angular.isDefined(changes.myBinding.currentValue)) {
                    if (!angular.equals(changes.myBinding.currentValue, changes.myBinding.previousValue)) {
                        myService.doSomething(changes.myBinding.currentValue).then(
                            function (data) {
                                ctrl.result = data;
                            }
                        );
                    }
                }
            }
        }
    }])
    .service('myService', ['$timeout', function ($timeout) {
        return {
            doSomething: function (x) {
                return $timeout(function () {
                    return x * 3;
                }, 500);
            }
        };
    }]);


/*
TEST GO HERE 
*/

describe('Testing a component controller', function () {
    var $scope, ctrl, $timeout, myService;

    beforeEach(module('myApp', function ($provide) {

    }));

    beforeEach(inject(function ($injector) {
        myService = $injector.get('myService');
        $timeout = $injector.get('$timeout');
    }));

    describe('with $componentController', function () {
        var scope;
        var controller;

        beforeEach(inject(function ($rootScope, $componentController) {
            scope = $rootScope.$new();
            scope.myBinding = 10;

            controller = $componentController('myComponent', {$scope: scope}, {myBinding: 10});
            controller.$onInit();
        }));

        it('should reflect to changes', function () {
            spyOn(myService, "doSomething").and.callThrough();
            controller.$onChanges({myBinding: {currentValue: 15, previousValue: 10}});
            $timeout.flush(); // resolve service promise 
            expect(myService.doSomething).toHaveBeenCalled(); // check if service method was called 
            expect(controller.result).toBe(45); // check controller's result value 
        });

    })

});
.as-console-wrapper {
  height:0;
}
<!DOCTYPE html>
<html>

  <head>
    <!-- jasmine -->
    <script src="//cdnjs.cloudflare.com/ajax/libs/jasmine/2.8.0/jasmine.js"></script>
    <!-- jasmine's html reporting code and css -->
    <script src="//cdnjs.cloudflare.com/ajax/libs/jasmine/2.8.0/jasmine-html.js"></script>
    <link href="//cdnjs.cloudflare.com/ajax/libs/jasmine/2.8.0/jasmine.css" rel="stylesheet" />
    
    <script src="//cdnjs.cloudflare.com/ajax/libs/jasmine/2.8.0/boot.js"></script>
    <!-- angular itself -->
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.js"></script>
    <!-- angular's testing helpers -->
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-mocks.js"></script>
  </head>

  <body>
    <!-- bootstrap jasmine! -->
  <script>
    var jasmineEnv = jasmine.getEnv();
    
    // Tell it to add an Html Reporter
    // this will add detailed HTML-formatted results
    // for each spec ran.
    jasmineEnv.addReporter(new jasmine.HtmlReporter());
    
    // Execute the tests!
    jasmineEnv.execute();
  </script>
  </body>

</html>

P.S。: $onChange不是组件生命周期挂钩的有效名称。它should be $onChanges