$scope属性在测试浏览器中更新,但不在测试中更新



test file:

describe('$rootScope', function() {
    describe('$on', function() {
        var credentials = "Basic abcd1234";
        var $scope;
        var $rootScope;
        var $httpBackend;
        ...
        beforeEach(inject(function($injector, $controller, _$rootScope_, $state, _$q_, currentUserService) {
            $scope = _$rootScope_.$new();
            $rootScope = _$rootScope_;
            $httpBackend.when('GET', 'dist/app/login/login.html').respond({'title': 'TEST_TITLE'}, {'A-Token': 'xxx'});
        }));
        ...
        it('should set $scope.title if noAuthorization', function() {
            spyOn($rootScope, '$on');
            $controller('AppCtrl', {$scope: $scope});
            $rootScope.$broadcast("$stateChangeStart");
            $rootScope.$apply();
            expect($rootScope.$on).toHaveBeenCalled();
            expect($scope.title).toBe('TEST_TITLE');
        });
    });
});

在我的测试中,$scope.title 总是未定义的。 期望总是失败。我试过$emit、$apply等。这是在控制器内,在 $rootScope.on 方法内。

但是,如果我在 js 文件中控制台日志 $scope.title,它确实表明 $scope.title 已更新。

我还应该提到被调用的函数不在$scope,即它不是$scope.updateTitle,它只是function updateTitle(...)

我觉得没有必要显示实际代码,因为它确实是它的工作。我只是想知道为什么测试中的$scope没有得到更新。

简而言之:不要忘记.andCallThrough()间谍。茉莉花间谍需要andCallThrough().使用element.scope()访问正确的范围。

spyOn(scope, '$apply').andCallThrough();

最新更新