【发布时间】:2015-03-27 08:52:57
【问题描述】:
我正在尝试为具有$rootScope.$on('accountsSet', function (event)... 的控制器编写测试。因此,在测试中,我使用了.broadcast.andCallThrough(),SO 中的许多其他问题都暗示了这些问题,而它以前也对我有用。
所以我的控制器非常简单:
angular.module('controller.sidemenu', [])
.controller('SidemenuCtrl', function($rootScope, $scope, AccountsService) {
$rootScope.$on('accountsSet', function (event) {
$scope.accounts = AccountsService.getAccounts();
$scope.pro = AccountsService.getPro();
});
});
任何测试也很简单:
describe("Testing the SidemenuCtrl.", function () {
var scope, createController, accountsService;
beforeEach(function(){
angular.mock.module('trevor');
angular.mock.module('templates');
inject(function ($injector, AccountsService) {
scope = $injector.get('$rootScope');
controller = $injector.get('$controller');
accountsService = AccountsService;
createController = function() {
return controller('SidemenuCtrl', {
'$scope' : $injector.get('$rootScope'),
'AccountsService' : accountsService,
});
};
});
});
it("Should load the SidemenuCtrl.", function () {
accountsService.setPro(true);
spyOn(scope, '$broadcast').andCallThrough();
var controller = createController();
scope.$broadcast("accountsSet", true);
expect(scope.pro).toBeTruthy();
});
});
spyOn(scope, '$broadcast').andCallThrough(); 的错误。请注意,此测试的范围是 rootScope,所以这应该不是问题。
所以引用该行的错误: TypeError: 'undefined' 不是函数(评估 'spyOn(scope, '$broadcast').andCallThrough()') 在 .../tests/controllers/sidemenu.js:30
【问题讨论】:
-
您可能没有使用 jasmine 2.0 吗?语法改为 and.callThrough()
-
是的,就是这样!问题是我确实有
karma-jasmine: 0.3.5,但我还没有像文档所说的那样安装jasmine-core。这很奇怪? -
我不认为你需要单独的 jasmine-core,如果你的测试运行,无论如何:) 如果我的评论是解决方案,我会把它变成一个简短的答案,你可以接受.
标签: javascript angularjs unit-testing jasmine karma-jasmine