Angular5 - 测试一个调用内部http服务的函数

时间:2018-06-04 10:38:30

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

我需要测试这个功能。

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

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

getallproductservice我测试此代码,但如何测试组件。

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 个答案:

答案 0 :(得分:0)

简单方法

let ws: ServiceName;

//in beforeEach    
ws= TestBed.get(ServiceName);

it('save should work', () => {
     spyOn(ws, 'getallproductservice').and.returnValue(
        of({})
      );;
     component.getallproductcomponent();
     expect(ws.getallproductservice).toHaveBeenCalled();
});

测试可观察量

import { marbles } from 'rxjs-marbles';
import { of } from 'rxjs/observable/of';

it(
    'should return the search result',
     marbles(marble => {
         const expectedResult={ item: {//something to match the api}}
         spyOn(ws, 'getallproductservice').and.returnValue(
            of(expectedResult)
          );
        component.getallproductcomponent();
        expect(component.item).toEqual(expectedResult.item);
      })