2013-02-02 46 views
0

應用程序中的所有內容都能正常工作,所以它只是我的語法錯誤的測試。這是我正在處理的截斷版本。名稱和地點已更改,以保護無辜者。JasmineJS無法識別我注入的模塊

var m; 

m = angular.module('CustomService', []); 

window.CustomService = m.factory("CustomService", function($rootScope) { 
    var sharedService; 
    sharedService = {}; 
    sharedService.broadcastItem = function() { 
    return console.log('Works!'); 
    }; 
    return sharedService; 
}); 

window.MyCtrl = function($scope, $location, CustomService) { 
    this.$inject = ['$scope', 'CustomService']; 
    return $scope.test_method = function(date) { 
    return CustomService.broadcastItem(date); 
    }; 
}; 

describe('MyCtrl', function() { 
    beforeEach(inject(function($rootScope, $controller, $location) { 
    this.scope = $rootScope.$new; 
    return this.controller = $controller(MyCtrl, { 
     $scope: this.scope, 
     $location: $location, 
     CustomService: CustomService 
    }); 
    })); 
    return it('tests my method', function() { 
    return this.scope.test_method('10-1984'); 
    }); 
}); 

這最後一行返回:

TypeError: Object #<Object> has no method 'test_method' 

奇怪!因爲我的整個應用程序都能正常工作,並且能夠完美實現該方法,所以一定是我沒有正確注入這個模塊(猜測!)。

回答

3

在你的代碼和測試中發生了很多事情,真的很難列出所有的東西。由於你沒有提供需要測試的實現(除了日誌),所以我扼殺了一些我認爲你想要做的和測試的東西,這對於完全幫助這個測試來說很難。

所以,這裏是測試:

describe('MyCtrl', function() { 

    var scope, controller; 
    beforeEach(module('CustomService')); 
    beforeEach(inject(function($rootScope, $controller, $location) { 
    scope = $rootScope.$new(); 
    controller = $controller('MyCtrl', { 
     $scope: scope 
    }); 
    })); 

    it('tests my method', function() { 
    scope.test_method('10-1984'); 
    expect(scope.brodcastedValue).toEqual('10-1984'); 
    }); 
}); 

測試的問題有:

  • 不正確的範圍創建($new()是方法而不是屬性
  • 缺乏參照模塊:beforeEach(module('CustomService'));
  • 指定給控制器的依賴關係太多

我還修改了代碼本身,以使測試通過:

m.factory("CustomService", function($rootScope) { 
    var sharedService; 
    sharedService = {}; 
    sharedService.broadcastItem = function(date) { 
    $rootScope.$broadcast('works', date); 
    }; 
    return sharedService; 
}); 

m.controller('MyCtrl', function($scope, $location, CustomService) { 

    $scope.test_method = function(date) { 
    CustomService.broadcastItem(date); 
    }; 

    $scope.$on('works', function(event, date){ 
    $scope.brodcastedValue = date; 
    }); 
}); 

不知道上面的是你的意圖或沒有。無論如何,它看起來像代碼從CoffeScript或其他東西(充滿了回報和這)轉換,所以我不知道我是否正確。

最後,工作普拉克,希望這一個會澄清所有細節: http://plnkr.co/edit/x2Jjvm8zwwaLZYV9aLfo?p=preview

+0

Pkozlowski,這是不可思議的。非常感謝你的幫助。您的工作對Angular社區給予了巨大的幫助。 – Trip

2

我注意到這條線在你的語法是一個錯誤:

this.scope = $rootScope.$new; 

而不是創建新範圍,如果引用$ rootScope的$新的功能。試試這個:

this.scope = $rootScope.$new();