首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用Jasmine Karma测试分支

使用Jasmine Karma测试分支
EN

Stack Overflow用户
提问于 2018-06-04 03:05:24
回答 1查看 6.3K关注 0票数 2

我想知道如何在Angular中使用Jasmin/Karma测试分支。例如,我有一个简单的函数:

代码语言:javascript
复制
  loadData(){
    if(this.faktor){ // here it should be true or false
      this.callMethod1();
    }else{
      this.callMethod2();
    }
  }

我将需要增加测试覆盖率,这是测试分支所必需的。我尝试了下面的例子,但它不起作用。我需要将this.factor.isExist()设置为true。我该怎么做呢?

这里是我的测试组件:

代码语言:javascript
复制
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();
  })
});
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-04 03:41:33

总是不可能使代码覆盖率达到100%,但您的情况非常简单,您可以覆盖此处显示的所有代码。

代码语言:javascript
复制
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();
  })
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50669985

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档