如何增加茉莉花的覆盖率摘要

How to increase the coverage summary in jasmine

我是 jasmine 和 karma 的新手。在增加组件方法的覆盖率摘要时遇到问题。

如何增加订阅块中出现的 if-else 条件的覆盖率?

我在 app.component.ts 文件中调用了一个服务方法。我必须根据结果验证响应并显示图像,但未涵盖覆盖范围。

app.component.ts

export class AppComponent {
  title = 'bank';
  flag: string;
  image: string;

  private regex: RegExp = new RegExp(/-(.*?)-/);

  constructor(private service : FlagService) {}

  ngOnit() {
    this.service.getFlag().subscribe(
      (res) => {
        this.flag = res.FlagModel[0].code.match(this.regex)[1];

        if(this.flag === 'dev') {
          this.image = '../assessts/icons/dev.png'
        } else if(this.flag === 'qa') {
          this.image = '../assessts/icons/qa.png'
        } else if(this.flag === 'prod') {
          this.image = '../assessts/icons/prod.png'
        } 
      }, (error) =>{
        console.log(error);
       });

  }
}

app.component.specs.ts

describe('AppComponent', () => {
  let component: AppComponent;
  let fixture: ComponentFixture<AppComponent>;
  let flagServiceTest: FlagService;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [
        AppComponent
      ],
      providers: [
        HttpClient,
        HttpHandler,
        FlagService
      ]
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
    flagServiceTest = TestBed.get(FlagService);
    fixture.detectChanges();
  });

  it('should create the app', () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.componentInstance;
    expect(app).toBeTruthy();
  });

  it(`should have as title 'bank'`, () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.componentInstance;
    expect(app.title).toEqual('bank');
  });

  it('should call subscribe method', fakeAsync(() => {
    const flagSpy = spyOn(flagServiceTest,'getFlag').and.callThrough();
    fixture.detectChanges();
    component.ngOnit();
    tick();
    expect(flagServiceTest.getFlag()).toHaveBeenCalled();
    expect(flagSpy).toHaveBeenCalled();
    expect(flagSpy.calls.any()).toBeTruthy();
  }));
});

期待 jasmine 包含以下块:

this.service.getFlag().subscribe(
      (res) => {
        this.flag = res.FlagModel[0].code.match(this.regex)[1];

        if(this.flag === 'dev') {
          this.image = '../assessts/icons/dev.png'
        } else if(this.flag === 'qa') {
          this.image = '../assessts/icons/qa.png'
        } else if(this.flag === 'prod') {
          this.image = '../assessts/icons/prod.png'
        } 
      }, (error) =>{
        console.log(error);
       });
  • 您需要为每个 if 语句创建一个测试用例,并且每次都需要从您的服务中提供合适的提要,因此我建议您使用间谍而不是引用真正的 FlagService
  • 创建一个全局夹具,这样您就不必为每个测试用例实例化它
  • 你不需要调用 .detectChanges 因为你已经调用了 ngOnInit.
    请参阅下面的项目,它涵盖了 100% 的 appComponent。 (https://github.com/IsmailDiari/Whosebug-anglar-jasmine-code-coverage).