【发布时间】:2014-08-05 21:14:11
【问题描述】:
如何检查是否在指令的单元测试中调用了 $emit?
我的指令相当简单(为了说明):
angular.module('plunker', [])
.directive('uiList', [function () {
return {
scope: {
lengthModel: '=uiList',
},
link: function (scope, elm, attrs) {
scope.$watch('lengthModel', function (newVal) {
scope.$emit('yolo');
});
}
}
}])
所以每次 uiList 属性发生变化时,都会发出事件。
我的单元测试代码如下:
describe('Testing $emit in directive', function() {
var scope;
var element;
//you need to indicate your module in a test
beforeEach(function () {
module('plunker');
inject(function ($rootScope, $compile) {
scope = $rootScope.$new();
scope.row= 1;
spyOn(scope,'$emit');
element = angular.element('<ul id="rows" ui-list="row">');
$compile(element)(scope);
});
});
it('should emit', function() {
scope.$digest();
scope.row = 2;
scope.$digest();
expect(scope.$emit).toHaveBeenCalledWith("yolo");
});
});
这总是会给我一个错误,说明 scope.$emit 从未被调用过。 范围有问题吗?有人可以帮忙吗?
【问题讨论】:
标签: angularjs unit-testing angularjs-scope karma-runner karma-jasmine