簡體   English   中英

為什么$ digest不更新單元測試中的范圍

[英]Why isn't $digest updating my scope in my unit test

我有以下代碼。 由於某種原因,測試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");
        });
    });
});

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);
                });
            }
        }
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM