Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing Angular $emit and $on events

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');

like image 206
user804401 Avatar asked Sep 25 '15 15:09

user804401


1 Answers

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.

like image 178
codemonkey Avatar answered Sep 22 '22 14:09

codemonkey