Angular 和 Jasmine - $scope函数未定义

Angular and Jasmine - $scope function is undefined

本文关键字:scope 函数 未定义 Jasmine Angular      更新时间:2023-09-26

我有一个控制器

var videoApp = angular.module('videoApp', ['videoAppFilters', 'ui.unique', 'angularUtils.directives.dirPagination']);
videoApp.controller('VideoCtrl', function ($scope, $http, $filter, cacheLoader, $rootScope) {
    $scope.setPageSize = function (pageSize) {
        $scope.pageSize = pageSize;
        return $scope.pageSize;
    };
    $scope.addFavorite = function (data, key) {
        localStorage.setItem(key, data);
        $scope.videos = $filter('articleFilter')(data, $scope.allData);
        return alert(key + " "+ data + " was added to your favorite list.");
    };
    $scope.addSelectedClass = function (event) {
        if($(event.target).hasClass("selected") == true)
        {
            $(event.target).removeClass("selected");
        } else {
            $(".selected").removeClass("selected");
            $(event.target).addClass("selected");
        }
    };
    $scope.filterArticles = function (category) {
        $scope.videos = $filter('articleFilter')(category, $scope.allData);
    };
    $scope.pageSize = 12;
    cacheLoader.load('http://academy.tutoky.com/api/json.php', true, function () {
        $scope.allData = $rootScope.allData;
        $scope.videos = $rootScope.videos;
        if(localStorage.getItem('category')) {
            $scope.videos = $filter('articleFilter')(localStorage.getItem('category'), $scope.allData);
        } else {
            $scope.videos = data;
        }
    });
});

和测试

describe('Check if VideoListCtrl', function() {
    beforeEach(module('videoApp'));
    beforeEach(inject(function (_$controller_) {
        $controller = _$controller_;
    }));
    beforeEach(inject(function ($rootScope) {
        $scope = {};
        controller = $controller('VideoCtrl', { $scope: $scope });
    }));
    it('exists', function() {
        expect(controller).not.toBeNull();
    });
    it('set page size', function () {
        expect($scope.setPageSize(12)).toEqual(12);
    });

});

我想测试控制器方法是否正常工作,但 Jasmine 会在第二次测试中出现错误:

类型错误:未定义不是函数

导致问题的事情是$scope.setPageSize(12)。我正在按照有关角度文档的教程进行操作,他们正在像那样使用范围的方法,但它在我的情况下不起作用。有人知道为什么吗?

我想你应该注意到在茉莉花中,"it"描述"是函数。

因此,当您需要在$scope内部测试某些东西时。你应该确保在任何"it"函数中,它都应该访问您的变量。

只需将您的测试用例更改为以下内容:

describe('Check if VideoListCtrl', function() {
    //Add an initialize here:
    var $scope = null;
    beforeEach(module('videoApp'));
    beforeEach(inject(function (_$controller_) {
        $controller = _$controller_;
    }));
    beforeEach(inject(function ($rootScope) {
        //new a $scope
        $scope = $rootScope.$new();
        controller = $controller('VideoCtrl', { $scope: $scope });
    }));
    it('exists', function() {
        expect(controller).not.toBeNull();
    });
    it('set page size', function () {
        expect($scope.setPageSize(12)).toEqual(12);
    });
});

或者您可以在角度文档中检查这一点。

希望这会起作用。