由于构造函数内部存在方法调用,因此无法进行角度单元测试

时间:2019-02-21 19:37:57

标签: angular karma-jasmine angular-testing spyon

由于组件构造函数中存在方法,因此无法运行角度单元测试。

 export class AppComponent  {
  name = 'Angular 4';
   constructor(){
    this.testMethod();
   }

   testMethod(){
         console.log("test method");
   }

  testMethodNonc(){
     console.log("test method nc");
  }
}

//我的规格文件

describe('MyComponent', () => {
  let fixture, element;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent  
      ]
    });

    fixture = TestBed.createComponent(AppComponent);
    element = fixture.debugElement;
  })
  it('works', () => {
    fixture.detectChanges();
    expect(component.testMethodNonc()).toHaveBeenCalled();
  });
});

当我尝试为testMethodNonc()运行单元测试时,功能testMethod()也与该方法一起运行,因为它存在于构造函数内部。可以通过模拟函数testMethod单独执行testMethodNonc()吗?

1 个答案:

答案 0 :(得分:2)

由于您正在创建该类的新实例,因此它将继续调用testMethod。您可以监视testMethod和callFake而不是调用方法。您也可以使用beforeAll而不是beforeEach,以便为测试只创建一次组件。这样,仅在创建组件时才调用该方法。

创建组件后,您可以调用所需的任何方法并分别进行测试。