我的组件单元测试中的测试服务电话

时间:2018-12-18 13:37:25

标签: angular unit-testing testing karma-jasmine

我将如何简单地测试我的服务已被调用?

myComp.ts

constructor(private myService: MyService) {}

myFunction() {
   this.myService.someFunction();
}

myTest.ts

beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [ReactiveFormsModule, FormsModule, HttpClientModule],
      declarations: [MyComponent]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should delete customer feed', () => {
    const mySpy = spyOn(MyService, 'someFunction');

    component.myFunction();

    expect(mySpy).toHaveBeenCalledTimes(1);
  });

当前,const mySpy = spyOn(MyService, 'someFunction');行在'someFunction'上显示红色弯曲,说明:

  

“ someFunction”类型的参数无法分配给原型类型的参数|服务|网址

更新 现在如何根据评论设置:

let myService: MyService;

beforeEach(() => {
  ...
  providers: [MyService],
  ...
  .compileComponents()
});

beforeEach(() => {
  fixture = TesBed.createComponent(MyComponent);
  component = fixture.componentInstance;
  fixture.detectChanges();

  myService = TestBed.get(MyService);
});

更新(解决方案) 我仍在间谍定义中使用大写MyService而不是小写myService!

1 个答案:

答案 0 :(得分:1)

您可以简单地继续spyOn您的服务方法以查看是否被调用。 您应该模拟该服务,然后在TestBedConfiguration上将其提供给您的组件。

您可以模拟所有服务方法,并根据需要返回任何值,以检查是否对您的服务方法进行了调用。

 class MyServiceStub {
     constructor(){}

     myFunction() { returns Observable.of({});}

    }
 let myService;
    beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [ReactiveFormsModule, FormsModule, HttpClientModule],
       providers: [
                { provide: MyService, useValue: new MyServiceStub() }
            ],
            schemas: [NO_ERRORS_SCHEMA]
      declarations: [MyComponent]
    })
    .compileComponents();
  }));

   beforeEach(() => {
     fixture = TestBed.createComponent(MyComponent);
     component = fixture.componentInstance;
       fixture.detectChanges();
    myService = TestBed.get(MyService);
    });

  it('should delete customer feed', () => {
    const mySpy = spyOn(myService , 'someFunction');

    component.myFunction();

    expect(mySpy).toHaveBeenCalledTimes(1);
   });

如果您不想使用存根模拟服务,则在TestBed.get(MyService)中向组件提供服务后,只需使用TestBed.configureTestingModule即可获取服务实例。