【问题标题】:unit test for Angular service when service doesn't return an Observable?当服务不返回 Observable 时对 Angular 服务进行单元测试?
【发布时间】:2019-05-30 13:16:25
【问题描述】:

我查看了 doc 以了解如何测试 http 请求,但我无法从文档中弄清楚如何对以下服务进行单元测试。

class service {

data$: BehaviorSubject<any> = new BehaviorSubject<>(any);

getDatas(): Observable<any> {
    this.http.get(url).subscribe((response) => {
       this.data$.emit(response);
    });
    // if return a observable will be like:
    // return this.http.get(url).

  }

}

如果上面的服务的方法没有返回 Observable,我该如何测试它?

【问题讨论】:

  • 监视data$ 并确保调用了emit
  • 谢谢,但是你粘贴的链接,它返回的 observable 与我的问题不同。

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


【解决方案1】:

The Head Rush 的评论是对的。这是我方便使用的代码示例。

服务

export class SomeService {
  constructor() {}

  goDoSomething(): void {
      console.log('I did something');
  }

}

测试

    describe('testing goDoSomething method', () => {
        it('should call console log', () => {
            spyOn(console, 'log'); // console is the object, and log is the method I expect to be called
            service.goDoSomething();
            expect(console.log).toHaveBeenCalled();
        });
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多