我正在尝试为 Controller 中的事件编写单元测试。
下面是我的 Controller
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
});
});
我期待更新父 Controller 中的消息, 但是测试在 expect(scope.message).toBe('Ralf ninja turtle');
最佳答案
您需要在调用 $emit
之后调用 $scope.$apply()
。这会在应用程序中自动发生,但需要在测试中显式调用。
关于javascript - 测试 Angular $emit 和 $on 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32785540/