使用 Angular 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)'
看起来链接函数从未被调用过,scope.$on 也是如此。
有人知道我如何实现这一目标吗? 谢谢
最佳答案
spyon 不起作用,因为链接函数在 jasmine speon 之前执行。
如果您确实想测试它,您可以在测试中广播该事件并检查事件处理程序结果。
关于javascript - 如何测试指令链接中定义的 $on 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36189205/