【问题标题】:How to mock a service call in a function in angular unit testing?如何在角度单元测试中模拟函数中的服务调用?
【发布时间】:2019-01-05 10:02:24
【问题描述】:

我正在尝试为以下函数编写一个测试用例:

foo = () => { 
  this.someService.getDetails({key:'value'}).subscribe(details => {
  //do stuff
    this.someService.getMoreDetails().subscribe(moreDetails => {
    //do stuff
   });
  });
}

服务如下所示:

    getDetails = (args) :Observable<any> {
      return this.http.post<any>(//calls)
    } 
// similar for getMoreDetails

我写的测试文件是这样的:

     const someServiceStub = jasmine.createSpyObj('someService', ['getDetails', 'getMoreDetails']);
...
...

    it('should called getMoreDetails', () => {
        component.foo();
        fixture.detectChanges();
        someServiceStub.getDetails.and.returnValue(Observable.of
          ({ Details: 'Tired of giving you details'})
        );
        expect(someServiceStub.getMoreDetails).toHaveBeenCalled();
      });

但是,我的测试用例未能给出错误“无法读取未定义的属性订阅”(对于 foo 函数内的第一行)。

我也尝试过使用 mockservice 类,但出现了同样的错误。 这可能是什么原因,我该如何解决?

【问题讨论】:

    标签: angular unit-testing jasmine karma-runner


    【解决方案1】:

    首先调用foo() 函数,该函数调用服务的getDetails() 方法。这个方法是一个间谍,你从来没有告诉间谍要返回什么,所以它返回 undefined。

    然后,你告诉间谍要返回什么。为时已晚:服务调用已经发出。告诉间谍在调用foo()之前返回什么。

    【讨论】:

    • 哦,我的极客,它有帮助。如果我必须在其他一些测试用例中进行测试,您能否建议如何继续,是否调用了 getMoreDetails(),我不想从 foo() 调用开始测试,而是直接从 getDetails() 的响应开始测试。 (简而言之,测试嵌套的 api 调用,无需重复测试函数中的前一行代码)
    猜你喜欢
    • 2019-06-05
    • 1970-01-01
    • 2016-08-02
    • 1970-01-01
    • 2020-07-10
    • 1970-01-01
    • 2021-09-18
    • 2020-06-24
    • 2018-11-11
    相关资源
    最近更新 更多