首页 > 解决方案 > 为什么 jasmin-karma-istanbul 报告中没有包含这个 if 语句

问题描述

所以这是一个奇怪的例子,一个语句没有被 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 的模拟函数返回具有所需值的类列表,语句也不会被覆盖。

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

标签: angularjasminekarma-jasmineistanbul

解决方案


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

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

您需要返回如下内容:

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


推荐阅读