测试将字符串转换为整数的angularjs指令

时间:2014-12-01 21:39:16

标签: javascript angularjs testing directive

好吧,我一直坚持测试我的指令:

angular.module('fooApp')
.directive('numericbinding', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        scope: {
            model: '=ngModel',
        },
        link: function (scope, element, attrs) {
            scope.$watch(attrs.ngModel, function () {
                if (!scope.model) {
                    // inits with default val
                    scope.model = 0;
                } else if (scope.model && typeof scope.model === 'string') {
                    // console.log('value changed, new value is: ' + (typeof scope.model));
                    scope.model = parseInt(scope.model);
                    // console.log('value changed, new value is: ' + (typeof scope.model));
                }
            });
        }
    };
});

单元测试:

'use strict';

describe('Directive: numericbinding', function () {

    var $compile;
    var $rootScope;

    beforeEach(module('fooApp'));

    beforeEach(inject(function(_$compile_, _$rootScope_, $httpBackend){
        $rootScope = _$rootScope_;
        $compile = _$compile_;

        $compile('<form name="form1"><input numericbinding ng-model="someModel.Property" name="data"></input></form>')($rootScope);
    }));

    it('converts string value to integer', inject(function () {
        $rootScope.someModel.Property = '10';
        // $rootScope.form1.data.$setViewValue('10')
        $rootScope.$digest();
        expect($rootScope.someModel.Property).toEqual(10);
    }));

}

msg失败:

PhantomJS 1.9.7 (Linux) Directive: numericbinding converts string value to integer FAILED
    Expected '10' to equal 10.

我已手动测试,stringinteger转换正常。这个特殊的测试仍然失败。

知道那个有什么问题吗?

更新

Chrome浏览器中的

调试显示:

scope.$watch(attrs.ngModel, function () {
我在测试中呼叫$rootScope.$digest();时未触发

。我甚至尝试过:$rootScope.$apply();但仍然没有变化。

0 个答案:

没有答案