AngularJS在Karma测试中设置范围变量

时间:2016-07-27 06:35:50

标签: javascript angularjs karma-jasmine

我正在尝试设置Karma单元测试,在我的测试中我想设置一个范围变量,以便我可以运行测试。我收到错误无法设置undefined的属性'expandedSeries'。

以下是我的代码。我做错了什么?

describe('FormController', function () {
    beforeEach(module('userFormApp'));
    var $controller;
    var $rootScope;

    beforeEach(inject(function (_$controller_, _$rootScope_) {
    $controller = _$controller_;
    $rootScope = _$rootScope_;
    }));

    describe('$scope.getImageSrc', function () {
    var $scope, controller;

    beforeEach(function () {
        $scope = $rootScope.$new();           
        controller = $controller('FormController', { $scope: $scope});
    });

    $scope.expandedSeries = 1;

    it('sets variables ', function () {
        expect($scope).toBeDefined();
        expect($scope.expandedSeries).toBeDefined();
        expect($scope.expandedSeries).toEqual(1);
    });
});

1 个答案:

答案 0 :(得分:1)

在每个变量之前实例化变量,以便测试用例在启动时可以获取它。

describe('$scope.getImageSrc', function () {
var $scope, controller;

beforeEach(function () {
    $scope = $rootScope.$new();           
    controller = $controller('FormController', { $scope: $scope});
$scope.expandedSeries = 1;
});

    it('sets variables ', function () {
    expect($scope).toBeDefined();
    expect($scope.expandedSeries).toBeDefined();
    expect($scope.expandedSeries).toEqual(1);
});

});