I am trying to write unit test for my events in controller.
Below is my 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);
}
}]);
And below is my test that i am trying to write
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
});
});
I am expecting message in the parent controller to be updated, But the test is failing at expect(scope.message).toBe('Ralf ninja turtle');
You need to call $scope.$apply()
after the call to $emit
. This would happen automatically in the application, but needs to be called explicitly in the test.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With