How to trigger $onInit or $onChanges implictly in unit testing Angular component controller?

前端 未结 3 999
独厮守ぢ
独厮守ぢ 2021-02-13 04:20

I\'m using Angular 1.5.5 and Jasmine as test framework. Currently I have to do something like this so that the test passes:

function createController(bindings) {         


        
3条回答
  •  猫巷女王i
    2021-02-13 04:58

    You would require to take reference of controller from compiled version of element. As shown below:

    describe('Component: Test Method', function () {
    
            beforeEach(inject(function (_$rootScope_) {
                scope = _$rootScope_.$new();
            }));
    
    
            it('should set value of selectedPackage to null after $onChanges event', inject(function ($compile) {
                // Trigger 1st $onChanges
                scope.selectedPackage = 'packageCode';
    
                var element = angular.element('');
                element = $compile(element)(scope);
                scope.$digest();
    
                //Extract the Controller reference from compiled element
                var elementController = element.isolateScope().$ctrl;
    
                // Assert
                expect(elementController.selectedPackage).toBeNull();
            }));
        });
    });
    

提交回复
热议问题