【问题标题】:Why the next line is not being covered in unit test coverage?为什么下一行没有被单元测试覆盖?
【发布时间】:2020-09-24 17:14:41
【问题描述】:

我为以下函数运行 jasmin-Karma 测试

ExampleFunction(someParam) {
    let element = document.querySelector(`aSelectorId}`);
    if (element ) {
      element.classList.remove('disabled');
      element.classList.add('enabled');
    }
  }

这是我运行的测试

 describe('ExampleFunction', () => {
    it('it should enable and disable', () => {
      spyOn(document, "querySelector").and.callFake(function() {
        return {
              value: true
          }
      });
      componentInstance.ExampleFunction("params");
      expect(componentInstance.Somevalue).toBe(something);
    });
  });

现在的问题是代码覆盖率显示

 element.classList.remove('disabled');

如涵盖但不是这一行!

  element.classList.add('enabled');

大家能告诉我为什么会这样吗?

【问题讨论】:

    标签: angular jasmine karma-jasmine


    【解决方案1】:

    您在 spy 中指定的返回值没有 classList 属性。这应该会导致最后一行代码没有被执行。

    尝试在你的间谍中添加两个删除和添加方法:

    return {
      value: true
      classList: {
        remove: () => {},
        add: () => {}
      }         
    }
    

    或者,您还可以提供用于删除和添加的模拟,以便您也可以测试是否使用正确的属性调用方法。

    这可能看起来像这样:

        it('it should enable and disable', () => {
          const removeSpy = jasmine.createSpy();
          const addSpy = jasmine.createSpy();
    
          spyOn(document, "querySelector").and.callFake(function() {
            return {
                  value: true,
                  classList: {
                     add: addSpy,
                     remove: removeSpy
                  }
              }
          });
          componentInstance.ExampleFunction("params");
          expect(componentInstance.Somevalue).toBe(something);
          expect(addSpy).toHaveBeenCalledWith('enabled');
          expect(removeSpy).toHaveBeenCalledWith('disabled')
        });
    
    

    请注意,这是伪代码,我没有正确测试它,但它应该可以按照这些思路工作。

    看看jasmine documentation

    【讨论】:

    • 非常感谢,您能告诉我有关添加和删除的 mocs 吗?
    • 试试 jasmine.createSpy。看看我更新的答案。它是纯伪代码,因此您可能需要进行一些更改,但它应该向您展示总体思路
    • 当然,我只是错过了 :)
    • 嘿@Erbsenkoenig,我又遇到了一些问题,你能帮帮我吗?
    • 我可以看看。你能分享一个问题的链接吗?
    猜你喜欢
    • 2020-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-17
    • 2014-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多