Noa*_*ony 2 jasmine typescript karma-jasmine angular
我想知道如何在 Angular 中使用 Jasmin/Karma 测试分支。例如我有这个简单的功能:
loadData(){
if(this.faktor){ // here it should be true or false
this.callMethod1();
}else{
this.callMethod2();
}
}
Run Code Online (Sandbox Code Playgroud)
我需要增加测试覆盖率,并且需要测试分支。我尝试使用下面的示例,但它不起作用。我需要将 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();
})
});
Run Code Online (Sandbox Code Playgroud)
代码覆盖率始终不可能达到 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();
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10144 次 |
| 最近记录: |