【问题标题】:Branches on constructor not covered未涵盖构造函数上的分支
【发布时间】:2017-08-30 03:54:33
【问题描述】:

我正在使用 Jasmine 创建我的单元测试,我对所涵盖的分支有疑问。

有谁知道为什么代码部分显示没有覆盖分支,如下所示?

这是单元测试:

describe('MyComponent', () => {
  let component: MyComponent;
  let fixture: ComponentFixture<MyComponent>;
  let myService: MyService;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ MyComponent ],
      imports: [ MaterializeModule, FormsModule, ReactiveFormsModule, HttpModule ],
      providers: [
        MyService,
        FormBuilder
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    slotsService = TestBed.get(MyService);
    fixture.detectChanges();
  });

  function updateForm(name, surname) {
    component.myForm.controls['name'].setValue(name);
    component.myForm.controls['surname'].setValue(name);
  }

  it('should create', () => {
    expect(component).toBeTruthy();
  });
}

【问题讨论】:

  • 显示你的单元测试

标签: unit-testing angular jasmine karma-jasmine karma-coverage


【解决方案1】:

从我将项目升级到 angular 4 的那一刻起,几个月来我一直遇到同样的问题。不幸的是,这是 angular-cli 版本 1 和 angular 4 的错误。

此错误已记录在 angular-cli 项目中:Test-coverage says that coverage is not 100%, but it truly is! #5871。不幸的是,目前这个问题仍然悬而未决。

这是该已记录问题的快照,与您询问的问题相符:

【讨论】:

  • 我也面临同样的问题
【解决方案2】:

如果您遇到此问题,但仍希望达到 100% 的分支覆盖率,那么至少有一个可用的解决方法(请参阅https://github.com/angular/angular-cli/issues/5526#issuecomment-324429322)。

只需在类导出后添加/* istanbul ignore next */(不带任何换行符):

export class InternalComponent {
    constructor(private authService: any) { 
    }
} /* istanbul ignore next */

【讨论】:

    【解决方案3】:

    对于 Angular 2+ 项目,如果您升级到 Angular CLI 1.5,这个问题现在已得到修复。

    GitHub 帖子: https://github.com/angular/angular-cli/issues/5526

    【讨论】:

    • 给定的链接可能会解决问题。但是,如果链接被撤销,您的答案将变得毫无用处。所以请添加描述。
    【解决方案4】:

    确保您的组件中没有任何未使用的导入成员。 我也面临同样的情况,我已经删除了未使用的导入,它开始为我工作。

    【讨论】:

      猜你喜欢
      • 2016-06-27
      • 1970-01-01
      • 2021-05-10
      • 1970-01-01
      • 1970-01-01
      • 2014-06-09
      • 2017-05-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多