测试在组件Angular5中调用http服务的函数

时间:2018-06-04 14:27:12

标签: angular unit-testing testing jasmine karma-jasmine

我需要测试这个功能。

单击此功能getallproductcomponent()时,执行此服务功能getallproductservice()并返回所有产品。请问,如何在组件中进行测试?

  getallproductcomponent() {
    this.ws.getallproductservice().subscribe(
      item=> {
        this.item= item;
      }
    );
  }

我只能测试getallproductservice。下面你可以看到我的脚本运行良好。如何测试getallproductcomponent() {}

it('testing',
    async(inject([ProductService], (service: ProductService) => {
        TestBed.get(MockBackend).connections.subscribe(
            (connection: MockConnection) => connection.mockRespond(new Response(
                new ResponseOptions({
                                    })
            ))
        );
        service.getallproductservice().subscribe(items => {
            expect(items[0].alarmdesc).toEqual('call');
        });
    })))

请问好吗?

编辑:

it('should call service.getallproductservice when getallproductcomponent', done => {
    const mock = [ {id: 1, alarmdesc: 'test12'}];
    component['ws'].getallproductservice = () => Observable.of(mock);
    spyOn(component['ws'].and.callThrough();

    component['ws'].getallproductservice ().subscribe(items => {
        expect(component['ws'].getallproductservice ).toHaveBeenCalled();
        expect(component.item).toBe(mock);
        done();
    });
    component.getallproductcomponent();
}));

结果:

1:component['ws'].getallproductservice = () => Observable.of(mock); 错误:

  

输入'()=> Observable< {id:number; alarmdesc:string; } []>”不是   可分配给'()=>类型可观察到的”。

2:spyOn(component['ws'].and.callThrough(); 错误:

  

[ts]'ProductService'类型中不存在属性'和'。

1 个答案:

答案 0 :(得分:0)

在您的组件中,您应该测试您的服务。您不应该测试您的服务是否正在调用端点:这将在您的服务测试中完成。

这意味着您只需要测试:

it('should call service.getallproductservice when getallproductcomponent', done => {
  const mock = [/* mock of your objects */];
  component['ws'].getallproductservice = () => Observable.of(mock);
  spyOn(component['ws'], 'getallproductservice').and.callThrough();

  component['ws'].getallproductservice().subscribe(() => {
    expect(component['ws'].getallproductservice).toHaveBeenCalled();
    expect(component.item).toBe(mock);
    done();
  });

  component.getallproductcomponent();
});