为什么$ digest在我的单元测试中不更新我的范围

时间:2013-05-09 11:48:35

标签: javascript angularjs jasmine angularjs-directive

我有以下代码。由于某种原因,测试1失败了。谁能告诉我为什么?

angular.
    module('myModule', []).
    directive('myDirective', function () {
        return {
            restrict: 'E',
            scope: {
                myAttr: '='
            },
            link: function (scope, element, attrs) {
                element.text(scope.myAttr);
            }
        }
    });

describe('test', function () {
    var compile, rootScope;

    beforeEach(module('myModule'));

    beforeEach(inject(function ($compile, $rootScope) {
        compile = $compile;
        rootScope = $rootScope;
    }));

    describe('test 1', function () {
        it('test', function () {
            scope = rootScope.$new();

            // scope.myVar = "test";

            element = compile('<my-directive my-attr="myVar" />')(scope);
            scope.$digest();

            scope.myVar = "test";
            scope.$digest();

            expect(element.text()).toBe("test");
        });
    });

    describe('test 2', function () {
        it('test', function () {
            scope = rootScope.$new();

            scope.myVar = "test";

            element = compile('<my-directive my-attr="myVar" />')(scope);
            scope.$digest();

            scope.myVar = "test";
            scope.$digest();

            expect(element.text()).toBe("test");
        });
    });
});

1 个答案:

答案 0 :(得分:0)

element.text(scope.myAttr);需要包含在手表中,如下所示:

angular.
    module('myModule', []).
    directive('myDirective', function () {
        return {
            restrict: 'E',
            scope: {
                myAttr: '='
            },
            link: function (scope, element, attrs) {
                scope.$watch('myAttr', function () {
                    element.text(scope.myAttr);
                });
            }
        }
    });