How to unit test angularjs form?

前端 未结 4 1599
长情又很酷
长情又很酷 2020-12-13 10:41

I have been learning AngularJS and things have been going pretty smoothly regarding unit testing, but I\'ve reached a bit of a tricky spot.

Suppose I have a simple f

4条回答
  •  独厮守ぢ
    2020-12-13 11:06

    I'm not convinced this is the best way to unit test something like this but with some help from this answer on testing custom angular directives and some experimentation, I figured out a way to unit test the form.

    After installing karma-ng-html2js-preprocessor and configuring it, I managed to get a working unit test like this:

    var scope, form;
    
    beforeEach(function() {
      module('my-module');
      module('templates');
    });
    
    beforeEach(inject($rootScope, $controller, $templateCache, $compile) {
        scope = $rootScope.$new()
    
        ctrl = $controller('MyController'), {
            "$scope": scope
        }
    
        templateHtml = $templateCache.get('path/to/my/template.html')
        formElem = angular.element("
    " + templateHtml + "
    ") $compile(formElem)(scope) form = scope.form scope.$apply() } it('should not allow an invalid `width`', function() { expect(form.$valid).toBeTruthy(); form.number.$setViewValue('BANANA'); expect(form.number.$valid).toBeFalsy() });

提交回复
热议问题