如何在角度2单元测试中访问方法的局部变量

时间:2018-03-13 18:09:14

标签: angular jasmine karma-jasmine

我正在尝试使用typescript为角度为2的方法编写单元测试用例。因为我有一个局部变量决定调用哪个函数。

getData(){
    let condition = route.queryParam.refer;
    if(condition === 'productWithChild'){
         this.LoadProductWithChildData(); 
    } else if(condition === 'product') {
         this.LoadProduct();
    }else{
        this.showMessage('No Data is Available');
    }
}

请建议如何为此方法编写单元测试用例。

1 个答案:

答案 0 :(得分:0)



// Code to test:
getData(){
    let condition = route.queryParam.refer;
    if(condition === 'productWithChild'){
         this.LoadProductWithChildData(); 
    } else if(condition === 'product') {
         this.LoadProduct();
    }else{
        this.showMessage('No Data is Available');
    }
}

// Sample code, but not complete:
describe('getData()', () => {
  it('should call the LoadProductWithChildData() function when the route.queryParam.refer value is "productWithChild"', () => {
    // Mock your route.queryParam.refer value here.
    component.route = {
      queryParam: {
        refer: 'productWithChild'
      }
    };
    spyOn(component, 'LoadProductWithChildData');
    
    expect(component.LoadProductWithChildData)
      .toHaveBeenCalled();
  });
  
  // Repeat the above for each of the conditions you have in your if()else() block.
});