Joh*_*art 5 javascript unit-testing jasmine angularjs
我正在尝试对绑定到ngClick指令的函数进行单元测试.它现在看起来像这样,因为我们刚刚开始这个项目,在我到达目前之前我想要一些测试覆盖:
vm.open = function($event) {
$event.preventDefault();
$event.stopPropagation();
vm.opened = true;
};
Run Code Online (Sandbox Code Playgroud)
我这样单元测试:
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();
});
});
Run Code Online (Sandbox Code Playgroud)
当Karma运行测试时,我收到此错误:
TypeError: $event.stopPropagation is not a function.
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
您的问题是stopPropagation该$broadcasted事件没有方法.广播向下传播和停止传播(可用$emit)用于防止进一步向上传播.所以你有2个选择.
要么使用 $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();
});
Run Code Online (Sandbox Code Playgroud)
或者只是为事件创建一个模拟对象.
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();
});
Run Code Online (Sandbox Code Playgroud)
另请注意,您确实不需要测试,expect(event.defaultPrevented).toBeTruthy();或者expect(event).toBeDefined();因为这是在调用preventDefault且已经过测试时的核心角度功能.