簡體   English   中英

Angularjs - Jasmine范圍變量在測試中未定義

[英]Angularjs - Jasmine scope variable undefined in test

我正在嘗試測試我的angularjs代碼。

我的控制器像bollow一樣。

'use strict';
(function() {
     angular.module('myApp')
    .controller('TestController', function($scope, $http, Auth, myService, $state) {
        try{
              $scope.testVar  = "Hello";
        }catch(e){
           console.log(e);
        }
     });
});

我的測試代碼如下:

'use strict';

 describe('Controller: TestController', function () {

     beforeEach(module('myApp'));

     var TestController, scope;

     beforeEach(inject(function ($controller, $rootScope) {
        scope = $rootScope.$new();

        TestController = $controller('TestController', {
             $scope: scope
        });
      }));

     it('should testVar to be defined', function () {
       expect(scope).toBeDefined();
       expect(scope.testVar).toBeDefined();
      });
});

當我運行它時,它未通過測試,因為Expected undefined to be defined.

我不知道我做錯了什么?

我已經在SO上查了很多帖子,但還沒有得到解決。

可能問題與您的變量聲明有關。 您已經聲明了ManualBookingController,但是您將$ Control行使用TestController。 將ManualBookingController更改為TestController,看看是否有效。

我把你的代碼幾乎按原樣,把它放在一個小提琴里 ,測試通過就好了。 在您的情況下,我認為可能缺少的是您在控制器中存在一些依賴項,但在使用測試套件中的$controller創建模擬控制器時不會進行模擬。 我從原來的控制器中刪除了它們(現在)並且工作正常。

並且為了模擬$state (提供者)和其他服務,你可以看到這個相同的例子小提琴傳遞依賴注入和讀取下划線包裝


另外,請記住,在您的問題上分享確切的詳細信息非常重要。 當我使用您的確切代碼運行您的測試套件時,它首先給了我以下錯誤:

Error: [$injector:unpr] Unknown provider: $stateProvider <- $state http://errors.angularjs.org/1.2.9/ $ injector / unpr?p0 =%24stateProvider%20%3C-%20%24state

..在你的問題中根本沒有提到。 你只提到了下一個錯誤Expected undefined to be defined ,這是非常常見的,並且無法想象發生了什么。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM