如何使用 jasmine 编写单元测试以覆盖 angular 控制器中的 DOM
How to write unit test using jasmine to cover DOM in angular controller
我在为 angular JS 中的一个控制器编写单元测试时遇到了问题。我正在使用 Karma jasmine 2.8.0.
控制器代码:-
var checkedlength = angular.element(e.target).parents('checkbox').find('input[type="checkbox"]:checked').length;});
if(checkedlength === 0){/* code here */}
else {/* code here */}
其中 e
是事件。
我想用 jasmine 编写单元测试,这样 if 和 else 部分都可以被覆盖。
如有任何帮助,我们将不胜感激。
模拟 angular.element 调用。像这样的东西。它不完整,但应该可以帮助您入门。
var arrayOfCheckboxes = ['checbox1', 'checkbox2'];
var angularSpy;
var elementFunction = function(e){ return anyMockedElement; }
var domCheckBoxes = {
find: function(searchString){
if(string === 'input[type="checkbox"]:checked'){
return arrayOfCheckboxes;
}
}
}
var anyMockedElement = {
parents: function(string) {
if(string === 'checkbox'){
return domCheckBoxes;
}
}
}
beforeEach(function() {
angularSpy = spyOn(angular, 'element').andCallFake(elementFunction);
});
afterEach(function() {
angularSpy.andCallThrough();
});
我在为 angular JS 中的一个控制器编写单元测试时遇到了问题。我正在使用 Karma jasmine 2.8.0.
控制器代码:-
var checkedlength = angular.element(e.target).parents('checkbox').find('input[type="checkbox"]:checked').length;});
if(checkedlength === 0){/* code here */}
else {/* code here */}
其中 e
是事件。
我想用 jasmine 编写单元测试,这样 if 和 else 部分都可以被覆盖。
如有任何帮助,我们将不胜感激。
模拟 angular.element 调用。像这样的东西。它不完整,但应该可以帮助您入门。
var arrayOfCheckboxes = ['checbox1', 'checkbox2'];
var angularSpy;
var elementFunction = function(e){ return anyMockedElement; }
var domCheckBoxes = {
find: function(searchString){
if(string === 'input[type="checkbox"]:checked'){
return arrayOfCheckboxes;
}
}
}
var anyMockedElement = {
parents: function(string) {
if(string === 'checkbox'){
return domCheckBoxes;
}
}
}
beforeEach(function() {
angularSpy = spyOn(angular, 'element').andCallFake(elementFunction);
});
afterEach(function() {
angularSpy.andCallThrough();
});