用Jasmine Karma测试一个分支

时间:2018-06-03 19:05:24

标签: angular typescript jasmine karma-jasmine

我想知道如何在Angular中测试Jasmin / Karma的分支。 例如,我有这个简单的功能:

  loadData(){
    if(this.faktor){ // here it should be true or false
      this.callMethod1();
    }else{
      this.callMethod2();
    }
  }

我需要增加测试覆盖率,并且需要测试分支。我尝试使用下面的示例,但它无法正常工作。我需要将this.factor.isExist()设置为true。我该怎么办?

以下是我的测试组件:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { ChartComponent } from './chart.component';

describe('ChartComponent', () => {
  let component: ChartComponent;
  let fixture: ComponentFixture<ChartComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ ChartComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ChartComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

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

  it('should call method1  if factor exist', () => {
    const spy =  spyOn(component, 'callMethod1');
    component.factor.isExist() as true;
    expect(spy).toHaveBeenCalled();
  })

  it('should call method2 if factor not exist', () =>{
    const spy =  spyOn(component, 'callMethod2');
    component.factor.isExist() as false;
    expect(spy).toHaveBeenCalled();
  })
});

1 个答案:

答案 0 :(得分:1)

始终无法使代码覆盖率达到100%,但是您的代码覆盖率非常简单,您可以在其中涵盖此处显示的所有代码。

it('should call method1  if factor exist', () => {
    const spy =  spyOn(component, 'callMethod1');
    component.factor = 'Your mock data goes here'
    component.loadData();       // should execute if part
    expect(spy).toHaveBeenCalled();
  })

  it('should call method2 if factor not exist', () =>{
    const spy =  spyOn(component, 'callMethod2');
    component.factor = null;    
    component.loadData();     // should execute else part
    expect(spy).toHaveBeenCalled();
  })