user1024941 user1024941 - 4 months ago 19
Javascript Question

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

Answer

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

});

Comments