CaptainMorgan
CaptainMorgan

Reputation: 1253

AngularJS set scope variables in Karma test

I'm trying to set up Karma unit tests and in my test I want to set a scope variable so I can run the test. I get the error Cannot set property 'expandedSeries' of undefined.

Below is my code. What am I doing wrong?

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

Upvotes: 1

Views: 1597

Answers (1)

Vikash Kumar
Vikash Kumar

Reputation: 1718

Instantiate the variable in before each so that the test cases can get it when they start.

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

});

Upvotes: 2

Related Questions