【发布时间】:2014-08-16 04:50:21
【问题描述】:
我在进行这个简单的测试时遇到了很多麻烦。
我要测试的控制器中有一个$scope.$on 侦听器。我只是想确定它是在广播事件之后调用的。
为此,我认为以下代码会起作用:
describe("Testing the parent controller: ", function() {
var scope, ctrl;
beforeEach(function() {
module("myApp");
inject(function($rootScope, $controller) {
scope = $rootScope.$new();
ctrl = $controller('parent-ctrl', {
$scope: scope,
});
});
});
it ("should trigger broadcast when current page updates", function() {
spyOn(scope, "$on");
scope.$broadcast("myEvent", 999);
expect(scope.$on).toHaveBeenCalled();
});
});
它没有 (Expected spy $on to have been called.)。我已经挖掘了很多例子:
- How do I test an event has been broadcast in AngularJS? in-angularjs
- How do I test $scope.$on in AngularJS
- How can I test events in angular?
- unit test spy on $emit
- How do I unit test $scope.broadcast, $scope.$on using Jasmine
- How do I test $scope.$on in AngularJS
- How can I test Broadcast event in AngularJS
学到了很多,但出于某种原因,我只是没有建立一些关键的联系。
我注意到$on 处理程序确实在断言后做出响应,这是无益的。我在各种配置中尝试过scope.$apply() 和.andCallThrough(),但似乎没有任何效果。
这是怎么做到的?
【问题讨论】:
-
你不应该在你的范围内调用 $digest() 吗?
标签: angularjs unit-testing events angularjs-scope jasmine