我正在尝试在控制器中触发
到目前为止,我已经成功测试了相应的
我试图在我的测试中直接使用
这是我的控制器:
这是我的测试:
$scope.$on()
方法,该方法在我$rootScope.broadcast()
一个事件时被触发。我发现这个问题很有用:如何测试Angular中的事件?,但是我仍然无法检测$rootScope
通过控制器的$scope
广播的事件。到目前为止,我已经成功测试了相应的
$rootScope
上调用了$broadcast
方法,但没有测试到$rootScope
上调用$broadcast
后相应的$scope
上是否调用了$on
方法。我试图在我的测试中直接使用
$rootScope.$broadcast
,但我的spy没有监听到事件。这是我的控制器:
angular.module('app.admin.controllers.notes', [])
.controller('NotesCtrl', function($scope) {
$scope.$on('resource-loaded', function(event, resource) { // I want to test this
$scope.parentType = resource.type;
$scope.parentId = resource.id;
});
});
这是我的测试:
describe('The notes controller', function() {
beforeEach(module('app.admin.controllers.notes'));
var scope, rootScope, NotesCtrl;
beforeEach(inject(function($controller, $injector, $rootScope) {
rootScope = $rootScope;
scope = $rootScope.$new(); // I've tried this with and without $new()
NotesCtrl = $controller('NotesCtrl', {$scope: scope}); // I've tried explicitly defining $rootScope here
}));
it('should respond to the `resource-loaded` event', function() {
spyOn(scope, '$on');
rootScope.$broadcast('resource-loaded'); // This is what I expect to trigger the `$on` method
expect(scope.$on).toHaveBeenCalled();
});
});
这里是plunkr链接。我包含了一个$broadcast
方法的通过测试,仅仅是为了参考,因为我以同样的方式设置了测试。
我读过很多关于在AngularJS中测试事件的问题,似乎总是涉及到作用域问题。我听说在Karma单元测试中,$rootScope
和$scope
是相同的东西,但我不确定影响是什么。我试过将$rootScope
和$scope
定义为同一个对象,也尝试在测试期间显式注入$rootScope
到NotesCtrl
中,但没有任何能让我的测试变为绿色的方法。
我该如何使得NotesCtrl
中的$on
方法在这个测试中被触发?