即使调用函数,toHaveBeenCalled也会失败

时间:2015-05-15 07:25:38

标签: angularjs angularjs-directive jasmine karma-jasmine

我有一个指令:

angular.module( 'app' )
    .directive( 'infiniteScroll', function() {
        return {
            scope: {
                canLoad: '=',
                fetchData: '&',
                viewportSelector: '@'
            },
            link: function( scope, element, attrs ) {
                var offset = parseInt( attrs.threshold ) || 0;
                var e = document.querySelector( attrs.viewportSelector );
                e.addEventListener( 'scroll', function() {
                    if ( scope.canLoad) {
                        scope.$apply( function() {
                            scope.fetchData();
                        } );
                    }
                } );
            }
        };
    } );

以下是我对此的测试:

describe( 'infiniteScroll directive : check ', function() {
    beforeEach( inject( function( $compile ) {
        scope.canLoad = true;
        element = angular.element( ' <div infinite-scroll fetch-data="addItems()" can-load="canLoad" viewport-selector=".selector">' );
        viewport = angular.element( ' <div class="selector" style="height:100px;width:100px;overflow-y:auto;"></div>' );
        var content = angular.element( ' <div style="height:800px;width:100px;"></div>' );
        viewport.append( content );
        angular.element( document.body ).append( viewport );
        angular.element( document.body ).append( element );
        element = $compile( element )( scope );
        scope.$apply();
        isolated = element.isolateScope();
    } ) );

    it( 'should check for scroll function', inject( function() {
        spyOn( isolated, 'fetchData' );
        viewport[ 0 ].scrollTop = 800;
        expect( isolated.fetchData ).toHaveBeenCalled();
    } ) );
} );

当我运行测试用例时,我可以看到(在istanbul覆盖报告中)我调用了scope.fetchData()但我的期望'expect(isolated.fetchData).toHaveBeenCalled()'失败。 我在这里做错了什么?

尝试通过以下方式等待:

    it( 'should check for scroll function', inject( function() {
        jasmine.clock().install();
        viewport[ 0 ].scrollTop = 800;
        jasmine.clock().tick( 2000 );
        expect( isolated.fetchData ).toHaveBeenCalled();
        jasmine.clock().uninstall();
    } ) );

但这也行不通。

0 个答案:

没有答案