【问题标题】:Function not covered in Jest Unit test even though the function was called in a test suite即使在测试套件中调用了该函数,Jest 单元测试也未涵盖该函数
【发布时间】:2021-10-08 14:12:01
【问题描述】:

我有一个<a /> 标签,如下所示:

 <a class="md-color--blue-50 md-link" (click)="resetdevicesearch()" >Reset filters</a>

在我的ts 文件中,函数是这样定义的:

resetdevicesearch() {
    const defaultsearchvalue = {value: {name: 'Any Name/Address', id: 1}};
    this.filterdeviceinfodata = {RisClass: '', Id: '', Name: ''};
    this.deviceonlyclicked = false;
    this.initform();
    this.devicesearch = {name: 'Phone', initial: 'Phone', id: 1};
    this.deviceStatus = this.devicesearchjson.PhoneDevice.DeviceStatus.devicestatusKey;
    this.updatestatus(this.devicesearchjson.PhoneDevice.DeviceStatus.defaultKey);
    this.updatedownloadstatus();
    this.updateProtocol();
    this.devicecheckboxvalue = [];
    this.selecttdefaultcheckbox(this.devicesearchjson.PhoneDevice.Monitorfollowingattribute.monitorfollowingattributeKey);
    this.enableinputfield(defaultsearchvalue);
    this.inputchange = {name: 'Any Name/Address', id: 1, label: ''};
    // @ts-ignore
    this.filterdeviceinfodata = {RisClass: '', Id: '', Name: ''};
  }

现在,我正在尝试编写一个Unit Test 来调用该函数。这是测试套件的样子:

 it('should get the anchor tag', () => {
    fakeAsync(() => {
      spyOn(component, 'resetdevicesearch');
      fixture.detectChanges();
      const input: ElementRef = fixture.debugElement.query(By.css('.md-link'));
      input.nativeElement.blur();
      tick();
      expect(page).toBeTruthy();
      expect(page.anchorTag).toBeTruthy();
      expect(component.resetdevicesearch).toHaveBeenCalled();
  });
  })

现在,测试运行成功,但是当我检查覆盖文件夹时,它显示Function not covered

为什么会这样?

编辑:

修改代码:

 it('should get the anchor tag', () => {
    fakeAsync(() => {
      jest.spyOn(component, 'resetdevicesearch');
      fixture.detectChanges();
      const input: ElementRef = fixture.debugElement.query(By.css('.md-link'));
      input.nativeElement.blur();
      tick();
      expect(page).toBeTruthy();
      expect(page.anchorTag).toBeTruthy();
      expect(component.resetdevicesearch).toHaveBeenCalled();
  });
  })

【问题讨论】:

    标签: angular testing jestjs


    【解决方案1】:

    在 Jasmine 中(或默认角度)spyOn(component, 'resetdevicesearch') 模拟函数调用,它不调用下划线函数。解决方法很简单,替换为:

    spyOn(component, 'resetdevicesearch').and.callThrough()
    

    an article 供您娱乐。

    但是,当使用 Jest(这是你的情况)the default 是通过调用,但你需要像这样使用它:

    jest.spyOn(component, 'resetdevicesearch')
    

    【讨论】:

    • 感谢您的解决方案。我修改了你提到的代码。但我仍然显示Function not covered
    • 我在上面的编辑中添加了修改后的测试套件。你能看看吗
    • 问题会是您的测试在模板链接click 事件时调用blur 事件吗?你能在测试中将blur() 更改为click() 吗?
    • 做了改变,还是一样的问题:(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-07
    • 1970-01-01
    • 2021-11-01
    • 2020-03-08
    • 1970-01-01
    相关资源
    最近更新 更多