How to unit test angularjs form?

前端 未结 4 1608
长情又很酷
长情又很酷 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:17

    Alternatively, if you are using WebPack with karma-webpack - you can include the template with require, without the need of karma-ng-html2js-preprocessor package:

    describe("MyCtrl's form", function () {
        var $scope,
            MyCtrl;
    
        beforeEach(angular.mock.module("my.module"));
    
        beforeEach(inject(function (_$rootScope_, _$controller_, _$compile_) {
            $scope = _$rootScope_.$new();
    
            // Execute the controller's logic
            // Omit the ' as vm' suffix if you are not using controllerAs
            MyCtrl = _$controller_("MyCtrl as vm", { $scope: $scope });
    
            // Compile the template against our scope to populate form variables
            var html = require("./my.template.html"),
                template = angular.element(html);
    
            _$compile_(template)($scope);
        }));
    
        it('should be invalid when given bad input', function () {
            MyCtrl.form.number.$setViewValue('Not a number');
            expect(MyCtrl.form.number.$valid).toBeFalsy();
            expect(MyCtrl.form.$valid).toBeFalsy();
        });
    });
    

    HTML:

提交回复
热议问题