gpt4 book ai didi

javascript - $event.stopPropogation 不是 Angularjs 单元测试中的函数错误

转载 作者:数据小太阳 更新时间:2023-10-29 05:57:47 24 4
gpt4 key购买 nike

我正在尝试对绑定(bind)到 ngClick 指令的函数进行单元测试。现在看起来像这样,因为我们刚刚开始这个项目,在我开始之前我想要一些测试覆盖率:

vm.open = function($event) {
$event.preventDefault();
$event.stopPropagation();
vm.opened = true;
};

我这样进行单元测试:

describe('Unit: simpleSearchController', function(){
//include main module
beforeEach(module('myApp'));
var ctrl, scope, event ;
// inject the $controller and $rootScope services
// in the beforeEach block
beforeEach(inject(function($controller, $rootScope){
// Create a new scope that's a child of the $rootScope
scope = $rootScope.$new();
// Create the controller and alias access using controllerAs
ctrl = $controller('simpleSearchController as vm', {
$scope: scope
});
}));
// unit tests
it('should set vm.opened to true', function(){
event = scope.$broadcast("click");
expect(event).toBeDefined();
scope.vm.open(event);
expect(event.defaultPrevented).toBeTruthy();
expect(scope.vm.opened).toBeTruthy();
});
});

当 Karma 运行测试时我得到这个错误:

TypeError: $event.stopPropagation is not a function. 

有什么想法吗?

最佳答案

您的问题是 $broadcasted 上没有stopPropagation 方法 事件。 broadcast 向下传播,而 stopPropagation(在 $emit 中可用)用于防止进一步向上传播。所以你有两个选择。

要么使用$emit

  it('should set vm.opened to true', function(){
event = scope.$emit("click");
expect(event).toBeDefined();
scope.vm.open(event);
expect(event.defaultPrevented).toBeTruthy();
expect(scope.vm.opened).toBeTruthy();
});

或者只是为事件创建一个模拟对象。

  it('should set vm.opened to true', function(){
event = jasmine.createSpyObj('event', ['preventDefault', 'stopPropagation']);
scope.vm.open(event);
expect(event.preventDefault).toHaveBeenCalled();
expect(scope.vm.opened).toBeTruthy();
});

另请注意,您真的不需要测试 expect(event.defaultPrevented).toBeTruthy();expect(event).toBeDefined(); 因为这是调用 preventDefault 时的核心 Angular 功能,并且已经过测试。

关于javascript - $event.stopPropogation 不是 Angularjs 单元测试中的函数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26512291/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com