【问题标题】:Angular5 - Test a function that calls a http service insideAngular5 - 测试一个调用内部http服务的函数
【发布时间】:2018-06-04 10:38:29
【问题描述】:

我需要测试这个功能。

当我点击这个功能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');
        });
    })))

【问题讨论】:

  • 您必须模拟/存根ws 服务,它是getallproductservice 方法。阅读Angular official documentaion 中的这篇文章,该文章描述了如何测试具有依赖关系的组件
  • 是的,我知道,但是如何在组件中实现,以及当我有一个调用内部http服务的函数时?

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


【解决方案1】:

简单的方法

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();
});

测试 observables

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);
      })

【讨论】:

  • 感谢您的回答。我尝试了简单的方法,结果是:TypeError: Cannot read property 'subscribe' of undefined
  • 我尝试了你的第一种方法。我不明白,我在服务器上有 10 个产品,当我把这个:expect(ws.getallproductservice).toEqual(100); 结果是:Expected 0 to equal 100.
  • 你应该模拟后端,在这种情况下是服务。
  • 拜托,我编辑我的帖子。我只能测试服务功能。如何实现此脚本和组件功能。谢谢
猜你喜欢
  • 2018-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多