TypeError: 'undefined' is not a function (evaluating 'scope.$on')

1.7k Views Asked by At

I got this test error when I have added a listener to my controller on search events from my layout controller.

This is the listener(placed it in a factory) and called it in my controller:

function listenToSearchRequest ( viewModel, scope ) {
    scope.$on( 'search:view', function ( event, data ) {
        viewModel.pageDetails.search = data;
        getRequest( viewModel, scope );
    } );
}

All of my tests have been working but ever since I tried listening to "search:view" event I keep on getting:

TypeError: 'undefined' is not a function (evaluating 'scope.$on')

A small snippet of my tests:

describe( 'User Classification Group Controller', function () {
    var controller;
    var $scope;
    var rs;
    var userClassifications = mockData.getMockPaginatedUserClassifications();

    beforeEach( function () {
        bard.appModule( 'app.admin' );
        bard.inject( '$controller', '$q', '$rootScope', '$log', 'authService', '$httpBackend', '$state', 'toastr', 'FORM_MSGS' );
    } );

    bard.verifyNoOutstandingHttpRequests();

    describe( 'when $scope.$parent is not available', function () {

        beforeEach( function () {
            $rootScope = {};
            $scope     = $rootScope;
            controller = $controller( 'ClassificationGroup', {
                '$scope' : $scope
            } );
        } );

        beforeEach( function () {
            $httpBackend.whenGET( '/api/userclassificationgroups/get_all_paginate/10?page=1&search=&sortField=&sortType=' ).respond( 200, userClassifications );
            $httpBackend.flush();
        } );

        it( 'should not set user classification group count', function () {
            expect( $scope.$parent ).to.equal( undefined );
        } );

    } );
} );

this is the error thrown:

PhantomJS 1.9.8 (Linux 0.0.0) User Classification Group Controller when $scope.$parent is not available "before each" hook for "should not set user classification group count" FAILED
TypeError: 'undefined' is not a function (evaluating 'scope.$on')

How do I mock scope.$on to avoid this error from all of my tests?

1

There are 1 best solutions below

0
On

Changing the test case code $scope to

      $scope = {'$on':function(){}};

Fixed this for me.