我需要测试事件是否正确发出或广播,并手动触发事件.
最好的方法是什么?
unit-testing javascript-events jasmine angularjs angularjs-directive
这个简单的测试工作我遇到了很多麻烦.
我$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();
});
});
Run Code Online (Sandbox Code Playgroud)
它没有(Expected spy $on to have been called.).我挖过很多例子:
并且学到了很多,但由于某种原因,我只是没有做出一些关键的联系.
我注意到$on处理程序确实响应后断言,这是无益的.我试着scope.$apply()和 …
我只是想知道如何测试这个handleAddClientBroadcast事件?
我有这样的导航服务:
angular.module("ruleManagement.services")
.factory('navigationService', function ($rootScope) {
var navigationService = {};
navigationService.prepForBroadcast = function() {
this.broadCastIsAddClientItem();
};
navigationService.broadCastIsAddClientItem = function() {
$rootScope.$broadcast('handleAddClientBroadcast');
};
return navigationService;
});
Run Code Online (Sandbox Code Playgroud)
我把这个导航服务注入到我的中,clientsCtrl然后抓住handleAddClientBroadcast这样的:
$scope.$on('handleAddClientBroadcast', function () {
$scope.clientModel = {
id: 0,
name: "",
description: "",
rules: []
};
var lastClient = _.findLast($scope.clients);
if (typeof lastClient == 'undefined' || lastClient == null) {
lastClient = $scope.clientModel;
}
$scope.clientModel.id = lastClient.id + 1;
$scope.clients.push($scope.clientModel);
});
Run Code Online (Sandbox Code Playgroud)
谢谢.