2015-04-22 26 views
1

我是karma-jasmine並嘗試開發一個演示測試用例。我得到的錯誤範圍未定義'它'。我已經閱讀了以下帶有相同問題的鏈接,但它並未幫助我完成測試用例。TypeError:範圍不明確Karma-jasmine-angular單元測試

Error Karma 'undefined' scope variable in beforeEach

TypeError: $scope is undefined in Angular controller unit test with Jasmine

This is my karma.conf.js

module.exports = function(config) { 
     config.set({ 

    exclude) 
     basePath: '', 


     frameworks: ['jasmine'], 

    files: [ 
      'js/angular.js', 
      'js/angular-mocks.js', 
      'app.js', 
      'test/**/*Spec.js' 
     ], 
     exclude: [ 
     ], 

     preprocessors: { 
     }, 
     reporters: ['progress'], 
     port: 9876, 

     colors: true, 

    config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG 
     logLevel: config.LOG_INFO, 

     autoWatch: false, 


     browsers: ['Firefox'], 

     singleRun: false 
     }); 
    }; 

Here is my mySpec.js where test code is written

describe('myApp', function() { 

    beforeEach(module('myApp')); 

    describe('HelloWorldController', function() { 

     var scope,HelloWorldController; 

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

     it('should assign message to hello world', function() { 
      expect(scope.greeting).toEqual('Hello World!'); 
     }); 
    }); 
}); 

And this is my app.js where controller is defined.

var myApp = angular.module('myApp',[]); 
myApp.controller('HelloWorldController', ['$scope', function($scope) { 
    $scope.greeting = 'Hello World!'; 
}]); 

,我得到的是錯誤,

TypeError: scope is undefined in** /home/abc/WebstormProjects/test1/test/basic/mySpec.js (line 17)

我不知道我在哪裏犯錯。請指導我解決這個問題。

在此先感謝。

+0

我不知道實際問題是什麼,但是當我安裝使用涼亭的角度文件它解決了我的問題。所以如果你沒有使用涼亭來安裝你的角度文件,那麼它可能會失敗。謝謝。 – James

+0

[AngularJS - 單元測試 - 作用域未定義]的可能重複(http://stackoverflow.com/questions/21928231/angularjs-unit-test-scope-undefined) –

回答

1

這裏的一個問題是一個錯字。 '範圍'是未定義的,因爲在您的控制器注入中,您將其定義爲'$ scope',但您期望的語句引用了'範圍':

describe('myApp', function() { 

    beforeEach(module('myApp')); 

    describe('HelloWorldController', function() { 

     var scope,HelloWorldController; 

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

     it('should assign message to hello world', function() { 
      expect(scope.greeting).toEqual('Hello World!'); 
     }); 
    }); 
});