[英]Testing Angular $emit and $on events
我正在嘗試為控制器中的事件編寫單元測試。
以下是我的控制器
myApp.controller('ParentCtrl', ['$scope', function ($scope) {
$scope.message = "Some text in parent";
$scope.$on("update_parent_controller", function(event, message){
$scope.message = message;
});
}])
.controller('ChildCtrl', ['$scope', function ($scope) {
$scope.clickFunction = function() {
$scope.message = "Parent updated from child controller";
$scope.$emit('update_parent_controller', $scope.message);
}
}]);
以下是我試圖寫的測試
describe("Hello Controller Test", function () {
var ctrl, scope;
beforeEach(module("myApp"));
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
spyOn(scope, '$on');
ctrl = $controller("ParentCtrl", {
$scope : scope
});
}));
it('should change ParentCtrl message property from child ctrl', function (){
var new_hero = 'Ralf ninja turtle',
sub_scope = scope.$new();
sub_scope.$emit('update_parent_controller', new_hero);
expect(scope.$on).toHaveBeenCalled();
expect(scope.message).toBe('Ralf ninja turtle'); //Getting err here
});
});
我希望更新父控制器中的消息,但是測試在期望失敗(scope.message).toBe('Ralf ninja turtle');
調用$emit
后需要調用$scope.$apply()
。 這將在應用程序中自動發生,但需要在測試中明確調用。
在測試用例scope.$on
被監視。
spyOn(scope, '$on');
為了調用實際函數,必須添加.and.callThrough()
。
spyOn(scope, '$on').and.callThrough();
這是一個完整的工作示例:
angular.module('myApp', []).controller('ParentCtrl', ['$scope', function ($scope) { $scope.message = "Some text in parent"; $scope.$on("update_parent_controller", function(event, message){ $scope.message = message; }); }]); describe("Hello Controller Test", function () { var ctrl, scope; beforeEach(module("myApp")); beforeEach(inject(function ($controller, $rootScope) { scope = $rootScope.$new(); spyOn(scope, '$on').and.callThrough(); // <-- This is the fix ctrl = $controller("ParentCtrl", { $scope : scope }); })); it('should change ParentCtrl message property from child ctrl', function (){ var new_hero = 'Ralf ninja turtle', sub_scope = scope.$new(); sub_scope.$emit('update_parent_controller', new_hero); expect(scope.$on).toHaveBeenCalled(); expect(scope.message).toBe('Ralf ninja turtle'); //Getting err here }); });
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.4/jasmine.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.4/jasmine.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.4/jasmine-html.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.4/boot.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular-mocks.js"></script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.