javascript - 在 AngularJS 事件单元测试中模拟事件对象

标签 javascript unit-testing angularjs angularjs-controller

我有以下测试:

    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/

相关文章:

javascript - 在输入中存储 AngularJS 表达式结果

javascript - 如何使用输入附加验证表单字段

c# - 如何设置这个Stub对象的返回值?

xcode - 为 RxSwift 编写单元测试

ios - 测试 Xcode 项目时无法访问 AppDelegate

css - Angular.js、ng 风格和 IE8

javascript - 将 video.js 集成到 Angular Web 应用程序中

javascript - 使用 ng-hide 和 radio 隐藏元素?

javascript - 将 img 的值复制到剪贴板(然后粘贴?)

javascript - 使用 XPage 中的 ClientSide JS 将值传递到新窗口