【问题标题】:Angular Shallow unit test with subscribe带有订阅的 Angular 浅单元测试
【发布时间】:2019-10-28 20:35:51
【问题描述】:

我通过 RxJS 订阅者的服务完成了组件间通信。

订阅这个的组件配置如下:

export class MyComponent implements OnInit, OnDestroy {
  constructor(
    private myService: myService,
    private datePipe: DatePipe
  ) {}

  ngOnInit(): void {
    this.mySubscription = this.myservice
      .getSubject()
      .subscribe(() => {
          //DO..SOMEYHING
          })
   }

 }

我们使用了 shallow 进行测试,myservice 的订阅的 next 事件被另一个组件调用。我们如何测试上面的代码块,因为我们在测试中模拟服务。

  beforeEach(async () => {
    shallow = new Shallow(MyComponent, MyModule)
      .mock(MyService, {

        getCount: () => of(25)
      })
  });

我们无法在测试中发送 myservice.setSubject,这会触发 ngInit 部分中的代码。

【问题讨论】:

    标签: angular testing karma-jasmine


    【解决方案1】:

    我会要求你发布服务代码,但我会尝试猜测主题的使用不是最推荐的(可能你有自己的原因)。

    我会有这样的服务:

    export class MyService {
        private subject = new Subject<number>();
    
        updateCount(n: number) {
            this.subject.next(n);
        }
    
        getCount(): Observable<number> {
            return this.subject.asObservable();
        }
    }
    

    在组件方面,在ngOnInit 方法中,我不会检索整个主题,但主题是可观察的,订阅将如下所示:

    this.myservice
          .getCount()
          .subscribe(() => {
              //DO..SOMEYHING
              })
    

    您提到下一个订阅由另一个组件调用。现在您可以在服务上使用 updateCount 方法,将逻辑集中在服务中,您可以更轻松地模拟它。

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 2020-09-23
      • 1970-01-01
      • 1970-01-01
      • 2022-01-01
      • 2021-06-28
      • 1970-01-01
      • 2017-11-23
      • 2018-10-03
      • 2018-02-01
      相关资源
      最近更新 更多