簡體   English   中英

單元測試需要ngModel的Angular 1.5組件

[英]Unit Testing Angular 1.5 component that requires ngModel

要測試angular 1.5組件,文檔建議您使用ngMock的$ componentController而不是使用$ compile,如果您不需要測試任何DOM。

但是,我的組件使用了我需要傳遞給$ componentController的locals的ngModel,但沒有辦法以編程方式獲取ngModelController; 測試它的唯一方法是實際$在其上編譯一個元素,因為這個問題仍然存在: https//github.com/angular/angular.js/issues/7720

有沒有辦法測試我的組件控制器而不采用$編譯它? 我也不想自己模仿ngModelController,因為它的行為有點廣泛,如果我的測試依賴於假的而不是真實的東西,那么新版本的Angular可能會破壞它(盡管可能不是'給定Angular 1的問題正在逐步淘汰)。

tl; dr:解決方案在第三個代碼塊中。

但是沒有辦法以編程方式獲取ngModelController

不是那種態度。 ;)

你可以通過編程方式獲得它,只是一個小環形。 這樣做的方法是ngMock$componentController服務的代碼中 (這里解釋); 使用$injector.get('ngModelDirective')來查找它,控制器函數將作為controller屬性附加到它:

this.$get = ['$controller','$injector', '$rootScope', function($controller, $injector, $rootScope) {
    return function $componentController(componentName, locals, bindings, ident) {
        // get all directives associated to the component name
        var directives = $injector.get(componentName + 'Directive');
        // look for those directives that are components
        var candidateDirectives = directives.filter(function(directiveInfo) {
            // ...
        });

        // ...

        // get the info of the component
        var directiveInfo = candidateDirectives[0];
        // create a scope if needed
        locals = locals || {};
        locals.$scope = locals.$scope || $rootScope.$new(true);
        return $controller(directiveInfo.controller, locals, bindings, ident || directiveInfo.controllerAs);
    };
}];

雖然您需要在實例化時為$element$attrs提供ngModelController本地。 ngModel的測試規范演示了如何在beforeEach調用中執行此beforeEach

beforeEach(inject(function($rootScope, $controller) {
    var attrs = {name: 'testAlias', ngModel: 'value'};


    parentFormCtrl = {
        $$setPending: jasmine.createSpy('$$setPending'),
        $setValidity: jasmine.createSpy('$setValidity'),
        $setDirty: jasmine.createSpy('$setDirty'),
        $$clearControlValidity: noop
    };


    element = jqLite('<form><input></form>');


    scope = $rootScope;
    ngModelAccessor = jasmine.createSpy('ngModel accessor');
    ctrl = $controller(NgModelController, {
        $scope: scope,
        $element: element.find('input'),
        $attrs: attrs
    });


    //Assign the mocked parentFormCtrl to the model controller
    ctrl.$$parentForm = parentFormCtrl;
}));

因此,根據我們的需要進行調整,我們得到如下規格:

describe('Unit: myComponent', function () {
    var $componentController,
        $controller,
        $injector,
        $rootScope;

    beforeEach(inject(function (_$componentController_, _$controller_, _$injector_, _$rootScope_) {
        $componentController = _$componentController_;
        $controller = _$controller_;
        $injector = _$injector_;
        $rootScope = _$rootScope_;
    }));

    it('should update its ngModel value accordingly', function () {
        var ngModelController,
            locals
            ngModelInstance,
            $ctrl;

        locals = {
            $scope: $rootScope.$new(),
            //think this could be any element, honestly, but matching the component looks better
            $element: angular.element('<my-component></my-component>'),
            //the value of $attrs.ngModel is exactly what you'd put for ng-model in a template
            $attrs: { ngModel: 'value' }
        };
        locals.$scope.value = null; //this is what'd get passed to ng-model in templates
        ngModelController = $injector.get('ngModelDirective')[0].controller;

        ngModelInstance = $controller(ngModelController, locals);

        $ctrl = $componentController('myComponent', null, { ngModel: ngModelInstance });

        $ctrl.doAThingToUpdateTheModel();
        scope.$digest();

        //Check against both the scope value and the $modelValue, use toBe and toEqual as needed.
        expect(ngModelInstance.$modelValue).toBe('some expected value goes here');
        expect(locals.$scope.value).toBe('some expected value goes here');
    });
});

附錄:您還可以通過在beforeEach注入ngModelDirective並在describe塊中設置var以包含控制器函數來進一步簡化它,就像使用$controller類的服務一樣。

describe('...', function () {
    var ngModelController;

    beforeEach(inject(function(_ngModelDirective_) {
        ngModelController = _ngModelDirective_[0].controller;
    }));
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM