我想知道如何在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();
})
});
发布于 2018-06-04 03:41:33
总是不可能使代码覆盖率达到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();
})
https://stackoverflow.com/questions/50669985
复制相似问题