我有以下测试:
it('Should keep location when user rejects confirmation', inject(function ($controller, $rootScope) {
var confirmStub = sinon.stub(),
eventStub = {
preventDefault: sinon.spy()
};
miscServiceStub = function () {
this.confirm = confirmStub;
};
confirmStub.returns(false);
initializeController($controller, 'Builder', $rootScope);
$rs.$broadcast('$locationChangeStart', eventStub);
expect(confirmStub).toHaveBeenCalledOnce();
expect(confirmStub).toHaveBeenCalledWith('Are you sure you want to leave? you will loose any unsaved changes.');
expect(eventStub.stopPropagation).toHaveBeenCalledOnce();
miscServiceStub = function () {};
}));
测试这段代码:
$rootScope.$on('$locationChangeStart', function (event) {
dump(arguments);
if (!$miscUtils.confirm('Are you sure you want to leave? you will loose any unsaved changes.')){
event.preventDefault();
}
});
event.$stopPropagation 不调用模拟事件,并且 dump(arguments) 显示它在真实事件对象之后被传递到事件中:
Chromium 31.0.1650 (Ubuntu) DUMP: Object{
0: Object{name: '$locationChangeStart', targetScope: Scope{$id: ..., $$childTail: ..., $$childHead: ..., $$prevSibling: ..., $$nextSibling: ..., $$watchers: ..., $parent: ..., $$phase: ..., $root: ..., this: ..., $$destroyed: ..., $$asyncQueue: ..., $$postDigestQueue: ..., $$listeners: ..., $$isolateBindings: ..., activeTab: ..., routeParams: ...}, preventDefault: function () { ... }, defaultPrevented: false, currentScope: Scope{$id: ..., $$childTail: ..., $$childHead: ..., $$prevSibling: ..., $$nextSibling: ..., $$watchers: ..., $parent: ..., $$phase: ..., $root: ..., this: ..., $$destroyed: ..., $$asyncQueue: ..., $$postDigestQueue: ..., $$listeners: ..., $$isolateBindings: ..., activeTab: ..., routeParams: ...}},
1: Object{stopPropagation: spy}
}
我怎样才能使事件对象成为模拟事件而不是真实事件对象本身?我以正确的方式接近这个吗?我是 Angular 的新手,非常感谢对代码/测试的任何评论。
如果您需要更多相关代码,请告诉我。
最佳答案
$scope.$broadcast
返回 Event
对象,因此您可以这样做:
var event = $scope.$broadcast("someEvent");
expect(event.defaultPrevented).toBeTruthy();
关于javascript - 在 AngularJS 事件单元测试中模拟事件对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21093506/