2016-03-23 31 views
1

使用angular 1.4.8和Karma 0.13.19,我想觸發一個在回調中定義的$回調函數,然後測試它是否根據回調得到的數據。

這裏是我的指令

(function() { 
    'use strict'; 

    angular.module('error').directive('errorPopup', function() { 
    return { 
     restrict: 'AE', 
     replace: true, 
     scope: {}, 
     templateUrl: 'components/error/error_popup-template.html', 
     link: function (scope, element, attrs) { 
      scope.$on('_REQUEST_ERROR_', function (event, response) { 
       scope.error = response; 
       console.log('on _REQUEST_ERROR_; scope.error: ', scope.error); 
       element.modal(); 
      }); 
     } 
    }; 
    }); 
})(); 

這裏是我的測試

describe('Error-Popup Directive', function(){ 
    var $templateCache, 
    scope, 
    element, 
    elementScope, 
    $compile, 
    listener = {}, 
    response; 

    beforeEach(module('error')); 

    beforeEach(inject(function ($templateCache, $compile, $rootScope) { 
    response = { 
     'data': { 
      'code': 'INVALID_AUTH_TOKEN', 
      'message': 'Authentication token is missing' 
     } 
    }; 
    $templateCache.put('components/error/error_popup-template.html', '<div>some html</div>'); 
    element = angular.element('<error-popup></error-popup>'); 

    scope = $rootScope.$new(); 

    // elementScope = element.scope; 
    spyOn(scope, '$on').and.callFake(function(event, callback) { 
     // Store event listeners for later access. 
     console.log('event:', event); 
     listener[event] = callback; 
     console.log('listener['+event+']:', listener[event]); 
    }); 

    $compile(element)(scope); 
    scope.$digest(); 
    })); 

    describe('scope.$on(\'_REQUEST_ERROR_\', callback)', function(){ 
    beforeEach(function(){ 
     listener['_REQUEST_ERROR_']({}, response); 
     console.log('scope:', scope); 
    }); 

    it('should set scope.error to response', function() { 
     expect(scope.error).toEqual(response); 
    }); 
    }); 
}); 

但我發現了TypeError: 'undefined' is not a function (evaluating 'listener['_REQUEST_ERROR_']({}, response)'

看起來鏈接功能不會被調用所以範圍。$上。

有沒有人有一個想法,我可以實現這一點? 謝謝

回答

1

spyon不起作用,因爲鏈接功能在jasmine spyon之前執行。

如果您真的想測試它,您可以在測試中廣播事件並檢查事件處理程序結果。

+0

我可以廣播一個事件,但事實證明scope.error測試時保持未定義,即使它通過偵聽器回調和scope.error已設置正確後(console.log證明它) – svassr

+0

你做了範圍。$適用()? – sdfacre

+0

不應該什麼時候應該執行'scope。$ apply()'?您在播出活動後使用 – svassr

相關問題