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

测试在组件Angular5中调用http服务的函数,angular,unit-testing,testing,jasmine,karma-jasmine,Angular,Unit Testing,Testing,Jasmine,Karma Jasmine,我需要测试这个函数 当我单击此函数时,执行此服务函数getallproductcomponent(),并返回所有产品。有什么想法吗?如何在组件中测试两者 getallproductcomponent() { this.ws.getallproductservice().subscribe( item=> { this.item= item; } ); } 我只能测试getallproductservice。下面你可以看到我的

我需要测试这个函数

当我单击此函数时,执行此服务函数
getallproductcomponent()
,并返回所有产品。有什么想法吗?如何在组件中测试两者

  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');
        });
    })))
有什么想法吗

编辑:

结果:

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

类型“()=>Observable”不可用 可分配给类型“()=>可观察”

2:In
spyOn(组件['ws'].and.callThrough();
错误:

[ts]属性“”和“”在类型“ProductService”上不存在


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

这意味着您只需测试:

it('getallproductcomponent'完成时应调用service.getallproductservice=>{
常量mock=[/*对象的mock*/];
组件['ws'].getallproductservice=()=>Observable.of(mock);
spyOn(组件['ws'],'getallproductservice')。和.callThrough();
组件['ws'].getallproductservice().subscribe(()=>{
expect(component['ws'].getallproductservice).toHaveBeenCalled();
expect(组件项).toBe(模拟);
完成();
});
getallproductcomponent();
});

Thnx获取答案。
TypeError:无法设置未定义的属性“getallproductservice”
我尝试了:`component['ws'].getallproductservice().subscribe(()=>{console.log(component.item)…`并且不执行,什么也不会发生。
getallproductservice()
不执行。您的服务必须被称为ws,这是您自己的代码。否则,请使用您提供的名称。当我输入ws时,
Type'()=>Observable'不能分配给Type'()=>Observable'。Type'Observable'不能分配给Type'Observable'。Type'boolean'不能分配给Type'Products[]“.
我想写mock而不是true,我的错!当我像这样写mock时,我编辑了我的答案,`const mock=[{id:1,alarmdesc:'test12'}];`is good?我试过了,
[ts]属性'和`type'ProductService'上不存在'
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();
}));