[AngularJS + Unit Testing] Testing a component with requiring ngModel

The component test:

describe('The component test', () => {
    let component, $componentController, $controller, $injector, $scope;

    beforeEach(module("componennts.module"));
    beforeEach(inject((_$componentController_, _$controller_, _$injector_, _$rootScope_) => {
        $componentController = _$componentController_;
        $controller = _$controller_;
        $injector = _$injector_;
        $scope = _$rootScope_.$new();
    }));

    describe('Controller', () => {
        it('should have ng-model with the correct binding', () => {    
            let locals = {
                $scope: $scope,
                $element: angular.element('<my-component ng-model="value"></my-component>'),
                $attrs: { ngModel: 'value' }
            };
            locals.$scope.value = [1];
            let ngModelController = $injector.get('ngModelDirective')[0].controller;
            let ngModelInstance = $controller(ngModelController, locals);
            $scope.$digest();
            component = $componentController('myComponent', null, { ngModel: ngModelInstance });
            component.$onInit();
            expect(component).toBeDefined();
            expect(component._selectedValues).toEqual([1]); // _selectedValues = ngModel.$viewValue
        });
    });
});
原文地址:https://www.cnblogs.com/Answer1215/p/9958978.html