TypeError:' undefined'不是一个功能(评估'范围。$ on')

时间:2015-10-08 01:28:12

标签: angularjs unit-testing sinon bardjs

当我在布局控制器的搜索事件中向控制器添加了一个监听器时,我遇到了这个测试错误。

这是监听器(放置在工厂中)并在我的控制器中调用它:

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

我的所有测试都一直在工作,但自从我尝试听取"搜索:查看"我继续得到的事件:

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

我测试的一小段内容:

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

    } );
} );

这是抛出的错误:

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

如何模拟范围。$ on以避免我的所有测试中出现此错误?

1 个答案:

答案 0 :(得分:0)

将测试用例代码$ scope更改为

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

为我解决了这个问题。