【问题标题】:How to write unit test using jasmine to cover DOM in angular controller如何使用 jasmine 编写单元测试以覆盖角度控制器中的 DOM
【发布时间】:2017-09-21 13:08:04
【问题描述】:

我在为 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 本质上只是一个 dom 查找。第三个 angularjs 不鼓励在控制器中进行 dom 操作。您应该使用指令进行 dom 操作。但我不确定你要做什么。正如我所说的没有足够的信息/代码
  • 感谢您的回复。
  • 我们已经编写了一个代码来根据复选框的数量进行操作。根据长度编写逻辑。为此,DOM 操作在控制器文件中完成。代码的编写方式使得 DOM 操作是在控制器本身中使用 angular.element 完成的。我们知道这不符合标准,但最初以某种方式错过了这一点,并且客户端强制要求 90% 的单元测试覆盖率才能进行部署。因此,我们正在尝试编写单元测试用例,但无法涵盖这些行,我们对此感到震惊。
  • 我们无法从 jasmine 文件中设置 angular.element(e.target).parents().find().length 的值,以便同时覆盖 if 和 else。如果我还需要更清楚地了解这个问题,请告诉我。
  • 如果你模拟 angular.element 调用,这应该是可行的。

标签: angularjs unit-testing dom jasmine karma-runner


【解决方案1】:

模拟 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();
});

【讨论】:

  • 谢谢大卫。当我们尝试您建议的相同方式但稍作修改时,效果很好。
  • 不客气。你能接受我的回答/或提供你的答案吗?
猜你喜欢
  • 2020-05-12
  • 1970-01-01
  • 2022-10-20
  • 2017-06-26
  • 1970-01-01
  • 2020-04-03
  • 2021-03-29
  • 2015-02-15
  • 1970-01-01
相关资源
最近更新 更多