【问题标题】:Why this if statement is not covered in jasmin-karma-istanbul report为什么 jasmine-karma-istanbul 报告中没有包含这个 if 语句
【发布时间】:2021-01-11 13:12:30
【问题描述】:

所以这是一个奇怪的例子,一个语句没有被 jasmin karma 测试运行器覆盖,这是正在测试的函数

aFunction(fewParams) {
   
    if (fewCondition) {
    
      let elements = document.querySelectorAll(`[id^=${aParam}]`);
      let anElement = find(elements, (el) => el.classList.contains('a-class-name'));
      if (anElement) {
         /* rest of the logic */
      }
      if (updatedConditions) {
        /*rest of the logic*/
      }
    }
  }

这是测试

 describe('aFunction', () => {
    it('it should do aFunctionality', () => {
      spyOn(document, "querySelectorAll").and.callFake(function() {
        return {
              value: true,
              classList: {
                remove: () => {},
                add: () => {},
                contains: () => { return ["a-class-name"] }
              }   
          }
      });
      componentInstance.aFunction("test", 1, true);
      expect(componentInstance.something).toBe(soemthing);
    });
  });

所以问题就在这里

if (anElement) { 

}

即使 querySelectorAll 的模拟函数返回具有所需值的类列表,也不会覆盖语句。

你能帮我解决这个问题吗?

【问题讨论】:

  • 与上一期类似,您的 querySelectorAll 仅返回一个元素,因此未定义 find,您需要返回一个列表,以便 find 实际返回一个元素 :)
  • 所以我需要在 ["a-class-name"] 数组中添加另一个元素吗?

标签: angular jasmine karma-jasmine istanbul


【解决方案1】:

如果你监视一个元素,它看起来就像在吞下任何运行时错误。

这与上一个问题非常相似,其中添加和删除未定义。这次的问题是,您正在模拟 querySelectorAll 方法,该方法需要返回一个数组,以便定义 find 方法。您正在返回一个对象,但该对象上不存在 find 方法。

您需要返回如下内容:

spyOn(document, "querySelectorAll").and.callFake(function() {
        return [{ // note the array here
              value: true,
              classList: {
                remove: () => {},
                add: () => {},
                contains: () => { return ["a-class-name"] }
              }   
          }]
      });

【讨论】:

  • 谢谢你很有用
猜你喜欢
  • 2012-05-11
  • 2017-01-26
  • 2019-11-06
  • 2019-12-11
  • 2011-12-03
  • 1970-01-01
  • 1970-01-01
  • 2021-08-03
相关资源
最近更新 更多