2016-03-23 6 views
1

angle 1.4.8とKarma 0.13.19を使用して、リンクで定義された$ onコールバックをトリガーして、スコーププロパティをコールバックが取得するデータ。ここで

は、ここに私の指示

(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

jasmine spyonの前にリンク機能が実行されているため、spyonが機能しません。

実際にテストしたい場合は、テストでイベントをブロードキャストし、イベントハンドラの結果を確認できます。

+0

イベントをブロードキャストできますが、scope.errorはリスナーコールバックを通過してscope.errorが正しく設定されていても未定義のままです(console.logはそれを証明します) – svassr

+0

$ apply()? – sdfacre

+0

いいえ、 'scope。$ apply()'はいつ行うべきですか? – svassr

関連する問題