【问题标题】:Unit testing Angular router.events.pipe followed by subscribe单元测试Angular router.events.pipe,然后订阅
【发布时间】:2022-01-01 07:11:06
【问题描述】:

我有以下角度代码:

changeMetaTags() {
  let metaData: any;
  this.router.events.pipe(
    filter(event => event instanceof NavigationEnd),
    map(() => {
      let child = this.activatedRoute.firstChild;
      while (child) {
          if (child.firstChild) {
            child = child.firstChild;
          } else if (child.snapshot.data) {
            return child.snapshot.data;
          } else {
            return null;
          }
      }
      return null;
    })
  ).subscribe( (data: any) => {
    metaData = data;
    if (data['title']) {
      this.translate.get(data['title']).subscribe((data: string) => {
        this.seoService.updateTitle(data);
      })
    }
  });

  this.translate.onLangChange.subscribe((event: LangChangeEvent) => {
    if (metaData['title']) {
      this.translate.get(metaData['title']).subscribe((metaData: string) => {
        this.seoService.updateTitle(metaData);
      })
    }
  });
}

我正在尝试为上述功能编写单元测试用例,但无法取得进展。任何人都可以帮助编写 changeMetaTags() 函数的 jasmine 单元测试。

如果您需要有关代码的更多详细信息,请发表评论。

提前谢谢你。

【问题讨论】:

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


    【解决方案1】:

    您可以使用https://angular.io/api/router/testing/RouterTestingModule#description 然后SpyLocation 来模拟路由器事件(导航),也可以将this.router.events 模拟为普通的Subject<RouterEvent> 并直接推送测试事件

    【讨论】:

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