$ compile不会将范围变量插入HTML

时间:2017-03-23 14:31:56

标签: javascript angularjs unit-testing jasmine

我想在单元测试中测试带有范围变量的HTML的渲染。

HTML有2 <textarea>,如下所示:

<textarea ng-model="a" ng-change="someFunction(a)" value={{a}}></textarea>
<textarea ng-model="b" ng-change="someFunction(b)" value={{b}}></textarea>

ab是范围变量,例如a = someFunction(b)b=someFunction(a)

说明:键入a会调用函数someFunction(a),该函数会更改textarea b中的文本。反之亦然b

我写的单元测试如下:

    var compile,
        scope,
        tc,
        template,
        controller,
        httpGuy;

    beforeEach(inject(function($compile, $rootScope, $templateCache, $controller, $httpBackend) {
        scope = $rootScope.$new();
        controller = $controller('ABCController', {'$scope': scope});
        compile = $compile;
        template = $templateCache.get('app/index.html');
    }));

it('test1', function() {
            scope.a = SOME_VALUE;
            scope.someFunction(scope.a);
            // at this point scope.b  changes to correct value
            var html_template = compile(template)(scope); // this should insert the scope variables in html?
            scope.$digest();
            console.log(angular.element(html_template.find('textarea')[1]));
        });

测试给出<textarea> value=""的输出,即空。值应该已经呈现,因为我们在HTML中引入了范围变量。 为什么不这样呢?

1 个答案:

答案 0 :(得分:1)

如果未设置$scope.bABCController的值,则该值将为""(空字符串)。

尝试在控制器中为它设置一些值,单位测试中<textarea>元素可以使用相同的值。

Here is the sample jsfiddle for the same

尝试在测试用例中将某些值设置为scope.ascope.b,然后编译不会将新指定的值插入已编译的dom,因为template将具有{{ 1}},它创建一个新的控制器实例(具有不同的范围)。因此,ng-controller='ABCController'对象上设置的值不会产生任何影响。

如果要将某些值设置为范围,然后想要使用特定范围对象编译scope,请从template中删除ng-controller并使用以下模式

template